简体   繁体   English

带有EntityType字段的Symfony 2.7 choice_attr

[英]Symfony 2.7 choice_attr with EntityType field

I need to add an additional HTML attribute to each choice of an EntityType field in Symfony 2.7. 我需要向Symfony 2.7中的EntityType字段的每个选择添加一个额外的HTML属性。

Following this guide, I assume that EntityType inherits this feature from ChoiceType. 遵循指南,我假设EntityType从ChoiceType继承了此功能。 I tried something like the following, but without effect; 我尝试了以下类似方法,但没有效果; no mytype attribute gets added to the rendered select options. 没有mytype属性被添加到呈现的选择选项。

$builder->add('customer_email', 'email')
        ->add('Product', 'entity', array(
              'class' => 'MyBundle:Product',
              'property' => 'name',
              'empty_value' => 'None',
              'required' => false,
              'choice_attr' => function ($val, $key, $index) {
                  return array('mytype' => $val->getType());
              }))

This is not necessarily the best answer, but I can't post comments yet. 这不一定是最好的答案,但是我还不能发表评论。

When implementing choice_attr, choice_labels etc... on ChoiceType and EntityType, it seems like choice_attr was left behind on the latter, there are a few comments about it on github, I personally need the same feature, hopefully it'll be implemented. 在ChoiceType和EntityType上实现choice_attr, choice_labels等...时,似乎choice_attr落后于后者,在github上有关于它的一些评论,我个人需要相同的功能,希望可以实现。

https://github.com/symfony/symfony/issues/4067 https://github.com/symfony/symfony/issues/4067

PS : Investigated further, it is indeed inherited from ChoiceType, and it only appears in the 2.7 documentation, if you write something like PS :进一步研究,它确实是从ChoiceType继承的,并且仅在2.7文档中出现,如果您编写类似

'choice_attr' => function (Product $product, $key, $index) {
    return ['class' => $product->getType() ];
}

You should get the class attribute set correctly, for custom attributes I am not sure, you might need to use 'attr' => 'foo' . 您应该正确设置class属性,对于不确定的自定义属性,可能需要使用'attr' => 'foo'

PPS .: Tested 'foo' =>'bar' and it works, no need to nest inside 'attr'. PPS 。:经过测试'foo' =>'bar'并且它起作用,不需要嵌套在'attr'中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM