Symfony2.3 setting value and innerHTML of a choicefield from a query

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Symfony2.3 setting value and innerHTML of a choicefield from a query



From a query I'm trying to personalize the choice field.



this is how I get the content of the select:


$em = $this->getDoctrine()->getManager();
$query2 = $em->createQuery("SELECT p.id,p.nombre FROM Exppromociones p");
$productos = $query2->getArrayResult();



The table should look like this:


{"id":93,"nombre":"Bucket"},
{"id":152,"nombre":"Spoon"},
{"id":142,"nombre":"Fork"}



With the variable $productos I build a form:


$form = $this->createFormBuilder()
->add('productos', 'choice', array('label' => 'Productos',
'required' => true,
'choices' => $productos,
))
->getForm();



And that form results to:


<optgroup label="0">
<option value="id">93</option>
<option value="nombre">Espumante Chandon Brut Nature</option>
</optgroup>



I want the choices field to have the value equal to the id and the innerHTML equal to nombre, like this:


<option value=93>Bucket</option>





Property choice_label will help you.
– u_mulder
2 days ago


choice_label





symfony.com/doc/current/reference/forms/types/…
– Cerad
2 days ago





@u_mulder Symfony2 doesn't have choice_label
– JHeisecke
2 days ago


choice_label





Symfony 2 have choice_label : symfony.com/doc/2.8/reference/forms/types/choice.html
– pbenard
yesterday





It has one but it won't do you any good for this problem. Just need to adjust your array per the example in the docs.
– Cerad
yesterday




1 Answer
1



I kept the same query


$em = $this->getDoctrine()->getManager();
$query2 = $em->createQuery("SELECT p.id,p.nombre FROM Exppromociones p");
$productos = $query2->getArrayResult();



but before creating my form builder I initialize an array, extract the id and nombre from "$productos" and load them into $choices


$choices=array();
foreach ($categorias as $cat){
$id=$cat['id'];
$nombre=$cat['nombre'];
$choices[$id] = $nombre;
}
$form = $this->createFormBuilder()
->add('categoria', 'choice', array('label' => 'Categoria',
'required' => true,
'choices' => $choices,
))
->getForm();



Now my options look like this


<option value=93>Bucket</option>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

iRofSAZX,RhgZ rDE,aguXKZxS1Yn5gHIEsM,7a 52 a0 M 7vgA s
mZuX4ocAFHl,i,VKxJ ZT68THdbSunSrC 4V SOOW8PJFeBG529bKt

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template