Reputation: 1543
When i create an entity field in Symfony2, how i can specify the value of the select option-field generated ?
This is the snippet of my entity 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 shown value through the property and it takes automatically the id referred to the db table. Good. What can i do, instead, whether i want to change the option value?
<option value="my_value">my_property</option>
Upvotes: 4
Views: 4566
Reputation: 1
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();
Upvotes: 0
Reputation: 717
I solved it by the following way:
code in FormType must 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 the data with DQL:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT u FROM MyBundle:Language ORDER BY u.id DESC');
$data = $query->getResult();
I pass the data through render method:
return $this->render('MyBundle:Default:page.html.twig',
array('formulario' => $formulario->createView(),
'data' => $data));
In the twig file, I create a <select>
item with id "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 data from the form, you can get it in the controller:
$form->get('preferred_language')->getData();
Upvotes: 1
Reputation: 911
also looked for same solution and found it here: different property for entity field type in form
just set the property in the field type options and create a getter for the property that formats the string the way to output the label.
Upvotes: 2
Reputation: 1847
If you create an "entity" field, you create a relation form between two entities, so the default field value is the id annoted field on your entity. You can change this behavior with a View Transformer. Check out this doc: http://symfony.com/doc/current/cookbook/form/data_transformers.html#model-and-view-transformers
Upvotes: 2