Roger Guasch
Roger Guasch

Reputation: 410

Symfony2 Forms with choice without optgroup

I have an array with the elements in a specific folder like this

$finder = new Finder();
$all_images = $finder->files()->in('images/questions');
$images = array();
foreach ($all_images as $image) {
     $images[$image->getRelativePathName()] = $image->getRelativePathName();
}

the var_dump output is:

 array (size=3)
      'image3.png' => string 'image3.png' (length=10)
      'image2.png' => string 'image2.png' (length=10)
      'image1.png' => string 'image1.png' (length=10)

and I create a "choice" element in my form like this:

->add('imageA', 'choice', array('choices' => array($images)

and I render this form element in twig like this (the css doesn't matters):

{{ form_widget(form.imageA, { 'attr': {'class': 'rounded' } }) }}

this generate this html code:

<select id="create_question_type_imageA" name="create_question_type[imageA]" class="rounded">
    <option value=""></option>
    <optgroup label="0">
        <option value="image3.png">image3.png</option>
        <option value="image2.png">image2.png</option>
        <option value="image1.png">image1.png</option>
    </optgroup>
</select>

I need this select without optgroup, I try expanded to false but doesn't work...

TY!

Upvotes: 1

Views: 1858

Answers (1)

Snroki
Snroki

Reputation: 2444

Since your $images variable is already an array you don't need to specify it as an array again in the form type. Else your $images will be an array of array, that's why Symfony added the optgroup.

Instead of :

->add('imageA', 'choice', array('choices' => array($images)

Try to simply set:

->add('imageA', 'choice', array('choices' => $images)

Upvotes: 9

Related Questions