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.
Symfony2 Setting a default choice field selection
"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);
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With