I need to add an additional HTML attribute to each choice of an EntityType field in Symfony 2.7.
Following this guide, I assume that EntityType inherits this feature from ChoiceType. I tried something like the following, but without effect; no mytype attribute gets added to the rendered select options.
$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.
https://github.com/symfony/symfony/issues/4067
P.S.: Investigated further, it is indeed inherited from ChoiceType, and it only appears in the 2.7 documentation, if you write something like
'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'
.
P.P.S.: Tested 'foo' =>'bar'
and it works, no need to nest inside 'attr'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With