Set default values ​​for the "field of non-display objects" in the form of Symfony 2

I got a Form class with an object field not showing 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 as follows:

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

How to set the default value? tried this but didn't work:

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

Please note that this is not a displayed field.

+5
source share
1 answer

Symfony2 Configuring default selection box selection

@Carrie Kendall answer:

"You will need to introduce an EntityManager in 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 the controller:

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

Source: https://habr.com/ru/post/1208426/


All Articles