Symfony2 Setting a default choice field selection Symfony2 Setting a default choice field selection symfony symfony

Symfony2 Setting a default choice field selection


You can define the default value from the 'data' attribute. This is part of the Abstract "field" type (http://symfony.com/doc/2.0/reference/forms/types/field.html)

$form = $this->createFormBuilder()            ->add('status', 'choice', array(                'choices' => array(                    0 => 'Published',                    1 => 'Draft'                ),                'data' => 1            ))            ->getForm();

In this example, 'Draft' would be set as the default selected value.


If you use Cristian's solution, you'll need to inject the EntityManager into your FormType class. Here is a simplified example:

class EntityType extends AbstractType{    public function __construct($em) {        $this->em = $em;    }    public function buildForm(FormBuilderInterface $builder, array $options){         $builder             ->add('MyEntity', 'entity', array(                     'class' => 'AcmeDemoBundle:Entity',                     'property' => 'name',                     'query_builder' => function(EntityRepository $er) {                         return $er->createQueryBuilder('e')                             ->orderBy('e.name', 'ASC');                     },                     'data' => $this->em->getReference("AcmeDemoBundle:Entity", 3)        ));    }}

And your controller:

 // ...     $form = $this->createForm(new EntityType($this->getDoctrine()->getManager()), $entity);// ...

From Doctrine Docs:

The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database. This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier.


the solution: for type entity use option "data" but value is a object. ie:

$em = $this->getDoctrine()->getEntityManager();->add('sucursal', 'entity', array(    'class' => 'TestGeneralBundle:Sucursal',    'property'=>'descripcion',    'label' => 'Sucursal',    'required' => false,    'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)           ))