在树枝模板中呈现自定义 formType 选项

Render custom formType option in twig template

我在 Symfony 2.8 中遇到了这个问题:我无法通过传递给表单选项的查询来呈现自定义变量。

查看下面的代码我已经尝试过:

这是我的控制器:

$form = $this->createForm('AppBundle\Form\FooAdminType', $res, array('attr' => array('fooOnes' => $Choices)));  
//when $choices is my dql query

这是我的表单类型:

public function buildForm(FormBuilderInterface $builder, array $options) {      
    $builder->add('bar', EntityType::class, array(
        'class' => 'AppBundle:Foo',
        'choices' => $options['attr']['FooOnes'],
        'required' => true,                    
        'property' => 'name',
        'attr' => array(
            'class' => 'col-lg-2 control-label text-center'
         )
    ))

最后,我的树枝模板

{% for foo in form.bar %}
    {{ form_widget(foo) }}
{% endfor %}

...没有 for 块,将呈现表单。使用 for 块,出现此错误:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string") in form_div_layout.html.twig at line 277.

PS: 我在实体

中定义了public function __toString()

如果不测试您的代码,按照您现在的设置方式,您将渲染一个 select 元素。因此,循环遍历它没有任何意义。

您需要将属性 expanded 设置为 true 以便您能够使用 for 循环。这样,您将呈现单选按钮或复选框,具体取决于多个值。

对于复选框:

public function buildForm(FormBuilderInterface $builder, array $options) {      
$builder
            ->add('bar', EntityType::class, array(
                'class' => 'AppBundle:Foo',
                'choices' => $options['attr']['FooOnes'],
                'required' => true,
                'expanded' => true,
                'multiple' => true,
                'property' => 'name',
                'attr' => array(
                    'class' => 'col-lg-2 control-label text-center'
                )
            ))