How to add custom attributes to option elements in symfony 2 form builder

Chase picture Chase · Oct 16, 2013 · Viewed 10k times · Source

I am trying to add custom attributes to the option elements using the symfony2 form builder im im not sure that is natively possible. If its not I need to know how i would go about adding the functionality.

Take the following form as an example:

class FooForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('user','choice',array(
            'choices' => array(
                 'designers'=>'designers',
                 '1'=>'mike',
                 '2'=>'carroll',
                 'developers'=>'developers',
                 '3'=>'chase',
                 '4'=>'brett',
                 '5'=>'jordan',
             )
        ));
    }
}

then when rendered i need it to look like:

<select>
    <option value="" disabled="disabled">designers</option>
    <option value="1">mike</option>
    <option value="2">carroll</option>
    <option value="" disabled="disabled">developers</option>
    <option value="3">chase</option>
    <option value="4">brett</option>
    <option value="5">jordan</option>
</select>

what i would expect would be something like:

class FooForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('user','choice',array(
            'choices' => array(
                 'designers'=>array(
                      'label'=>'designers',
                      'attr'=>arrry('disabled'=>'disabled')
                 ),
                 '1'=>'mike',
                 '2'=>'carroll',
                 'developers'=>array(
                      'label'=>'developers',
                      'attr'=>arrry('disabled'=>'disabled')
                 ),
                 '3'=>'chase',
                 '4'=>'brett',
                 '5'=>'jordan',
             )
        ));
    }
}

But that doesnt work. So any help on this will be greatly appreciated.

Answer

Fabian Picone picture Fabian Picone · Sep 15, 2015

Its possible for choice since 2.7. Look at here. With choice_attr.