Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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());
              }))
like image 220
dmb Avatar asked Dec 15 '15 13:12

dmb


1 Answers

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'.

like image 84
ABM_Dan Avatar answered Oct 05 '22 20:10

ABM_Dan