Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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.

Please use this below code for attribute set in symfony2

->add('birthdate', 'date',array(
      'input' => 'datetime',
      'widget' => 'single_text',
      'attr' => array('class'=>'calendar')
 ))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top