Symfony 2.7 choice_attr with EntityType field

I need to add an additional HTML attribute for each EntityType field selection in Symfony 2.7.

Following this guide, I assume EntityType inherits this function from ChoiceType. I tried something like the following, but with no effect; the mytype attribute is not added to the displayed selection 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()); })) 
+5
source share
1 answer

This is not necessarily the best answer, but I can not leave comments.

When implementing choice_attr, choice_labels , etc. on ChoiceType and EntityType it seems that choice_attr remained on the last, there are a few comments about it on github, I personally need the same function, I hope it will be implemented.

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

PS . Studied further, it is really 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 have to set the class attribute correctly, for custom attributes, I'm not sure you might need to use 'attr' => 'foo' .

PPS : Tested 'foo' =>'bar' and it works, there is no need to embed inside "attr".

+9
source

Source: https://habr.com/ru/post/1238260/


All Articles