Chase
Chase

Reputation: 9362

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.

Upvotes: 7

Views: 11533

Answers (3)

fabpico
fabpico

Reputation: 2927

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

Upvotes: 6

Arij
Arij

Reputation: 100

You might need to create own widget, extended from 'choice' widget.

So you'll be able to use custom render on your options, and you'll be able to setup whatever you want in attributes to each option.

NB: I was looking the same, but 've used simple 'choice', and in template I've added JS var with extra options (array with values from the 'select', and specified extra attributes). I apply each extra attributes based on values of he option on page load event.

Upvotes: 0

shashik493
shashik493

Reputation: 810

Please use this below code for attribute set in symfony2

->add('birthdate', 'date',array(
      'input' => 'datetime',
      'widget' => 'single_text',
      'attr' => array('class'=>'calendar')
 ))

Upvotes: -1

Related Questions