Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 664
Chase Avatar asked Oct 16 '13 00:10

Chase


Video Answer


1 Answers

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

like image 103
fabpico Avatar answered Sep 28 '22 22:09

fabpico