Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default values for a "non-mapped entity field" on a Symfony 2 form [duplicate]

Tags:

php

symfony

I got a Form class with a non-mapped entity field in it:

->add('client', 'entity', array(
    'class' => 'MyBundle:Client',
    'property' => 'name',
    'empty_value' => 'Select...',
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('c')
            ->orderBy('c.name', 'ASC');
    },
    'mapped' => false,
))

which I create like this:

$form = $this->createForm(new MyType(),
    $entity,
    array('action' => $this->generateUrl('my_action'))
);

How can I set it's default value ? tried this, but not worked:

'data' => 23423, // id in table 
'data' => 'Client name'
$form->setDefault('client', 'Client name'); // in controller

Please note that it's a non-mapped field.

like image 436
Nelson Teixeira Avatar asked Dec 05 '14 12:12

Nelson Teixeira


1 Answers

Symfony2 Setting a default choice field selection

@Carrie Kendall answer:

"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)
        ));
    }
}

In controller:

 // ...    

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

// ...
like image 174
Paweł Kolanowski Avatar answered Nov 11 '22 13:11

Paweł Kolanowski