1

Having form select field like:

$builder->add('foo', new ChoiceType, $this->defaults + [
                'choices'           => [/* some choices as key->value*/],
            ]);

I would like to add class to some of the options, so it renders like:

<select>
    <option value="1">foo</option>
    <option value="2">bar</option>
    <option value="3" class="showModal">baz</option>
</select>

How to achieve it? Important thing is that I would like to do this inside form type, not in template.

Similar problem has been described: here, but it was about input field.

Community
  • 1
  • 1
ex3v
  • 3,518
  • 4
  • 33
  • 55

1 Answers1

0

Stumbled on this post.. You can use the choice_attr option, like this :

        $builder
            ->add('cours', ChoiceType::class, [
                'choices' => $this->getCours(),
                'required' => true,
                'multiple' => false,
                'expanded' => false,
                'attr' => [
                    'class' => 'select2'
                ],
                'constraints' => [
                    new NotBlank(),
                ],
                'choice_attr' => function($choice, $key, $value) {
                    return ['class' => 'my_class'];
                },
            ])
        ;
Max
  • 891
  • 8
  • 17