symfony2 customize form select options symfony2 customize form select options symfony symfony

symfony2 customize form select options


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),));


use the data option as described here fo selected="selected" :http://symfony.com/doc/current/reference/forms/types/field.html

in ur case could be like this

$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'),            'data'=> 1            ));

the new element is data setting the number of the choice array as selected attribute


Every Field in symfony inherits from abstract field type, which has a data option, in which you can pass default option.

By the way, don't pass style stuff, and for custom attrs use data-* attributes.