Symfony2 - How to configure select labels for entity field type when using query_builder?

When I create an entity field in Symfony2, how can I specify the value of the generated select field?

This is a fragment of my object field:

->add('preferred_language', 'entity', array( 'mapped' => false, 'property' => 'name', 'class' => 'Common\MainBundle\Entity\Language', 'query_builder' => function(\Doctrine\ORM\EntityRepository $er) { return $er->createQueryBuilder('u') ->orderBy('u.id', 'DESC'); } 

Actually, I can specify the displayed value through the property and automatically accepts an identifier that refers to the db table. Good. What can I do instead, do I want to change the value of a parameter?

 <option value="my_value">my_property</option> 
+4
source share
4 answers

If you create an entity field, you create a relationship form between two objects, so the default value of the field is the field of the annotated identifier of your object. You can change this behavior with Transformer. Check out this document: http://symfony.com/doc/current/cookbook/form/data_transformers.html#model-and-view-transformers

+2
source

also searched for the same solution and found it here: another property for the entity field type in the form

just set the property in the field type parameters and create a getter for the property that formats the string, the way the label is displayed.

+2
source

I solved it as follows:

in FormType should be the same:

 ->add('preferred_language', 'entity', array( 'mapped' => false, 'property' => 'name', 'class' => 'Common\MainBundle\Entity\Language', 'query_builder' => function(\Doctrine\ORM\EntityRepository $er) { return $er->createQueryBuilder('u') ->orderBy('u.id', 'DESC'); } 

In the controller, I get data using DQL:

 $em = $this->getDoctrine()->getManager(); $query = $em->createQuery('SELECT u FROM MyBundle:Language ORDER BY u.id DESC'); $data = $query->getResult(); 

I pass data using the render method:

 return $this->render('MyBundle:Default:page.html.twig', array('formulario' => $formulario->createView(), 'data' => $data)); 

In the twig file, I create a <select> element with the identifier "myproject_mybundle_myformtype_ preferred_language ":

 <select id="myproject_mybundle_myformtype_preferred_language" name="aeneagrama_adminbundle_itemcontenidotype[preferred_language]" class="form-control"> <option value="0">-- Choose an option --</option> {% for item in data %} <option value="{{ item.your_column }}">{{ item.name }}</option> {% endfor %}</select> 

Finally, when you get input from the form, you can get it in the controller:

 $form->get('preferred_language')->getData(); 
+1
source

In your controller, make this change,

 $em = $this->getDoctrine()->getManager(); $query = $em->createQuery('SELECT u FROM MyBundle:Language u ORDER BY u.id DESC'); $data = $query->getResult(); 
0
source

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


All Articles