symfony2 customize form select options

Dariush Jafari picture Dariush Jafari · Aug 31, 2012 · Viewed 32.9k times · Source

I'm trying to do a simple form to add an activity with a name and a color.

So I want to make a list with some an array of color, for now it is working I have the name of the color.
I can add any attribute to my select tag:

$form = $this->createFormBuilder($myclass)
->add('Colors','choice',array('label'=>'select some colors',
            'multiple'=>true,
            'choices'=>array(1=>'red', 2=>'blue', 3=>'green'),
            'attr'=>array('style'=>'width:300px', 'customattr'=>'customdata')
            ));

The output will be something like this:

<select name="select" style="width: 300px;" multiple="multiple" customattr="customdata">
   <option value="1">red</option>
   <option value="2">blue</option>
   <option value="3">green</option>
</select> 

But how can I add selected="selected" and any attribute I want to my select options ? like this:

<select name="select" style="width: 300px;" multiple="multiple" customattr="customdata">
   <option style="background-color: #F00;" value="1" selected="selected">red</option>
   <option style="background-color: #00F;" value="2" selected="selected">blue</option>
   <option style="background-color: #0F0;" value="3">green</option>
</select> 

My question is: how can I add custom attr for option tag (not for select tag) by symfony FormBuilder.
NOTICE: I don't want to use JavaScript. I want to use symfony2 FormBuilder to customize my select options.

Answer

Bernhard Schussek picture Bernhard Schussek · Sep 1, 2012

Usually, the default data of a field is determined by the value stored in your object. For example, if

class MyClass
{
    private $Colors = array(1, 2);
}

then the entries "1" and "2" (with the labels "red" and "green") will be displayed as selected by default. You could also store this value in the object before passing it to the form:

$myObject->Colors = array(1, 2);

$form = $this->createFormBuilder($myObject)
    ...

The last possibility is to override the default value stored in the object by passing the "data" option:

$builder->add('Colors', 'choice', array(
    'label' => 'select some colors',
    'multiple' => true,
    'choices' => array(1 => 'red', 2 => 'blue', 3 => 'green'),
    'attr' => array('style' => 'width:300px', 'customattr' => 'customdata'),
    'data' => array(1, 2),
));