Symfony2可选择的表单,无需optgroup


Symfony2 Forms with choice without optgroup

我有一个数组,其中包含像这样的特定文件夹中的元素

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

var_dump输出为:

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

我在我的表单中创建了一个"选择"元素,如下所示:

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

我在trick中呈现这个表单元素如下(css无关紧要):

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

这将生成以下html代码:

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

我需要这个没有optgroup的选择,我尝试扩展到false,但不起作用。。。

TY!

由于$images变量已经是一个数组,因此不需要在表单类型中将其再次指定为数组。否则,$images将是数组的数组,这就是Symfony添加optgroup的原因。

代替:

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

尝试简单设置:

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