phpmysqlsymfonychoicefield

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">Bucket</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>

Solution

  • 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>