2016-11-28 60 views
3

我在Symfony 2.8中有这个问题:我无法呈现自定义变量,并将查询传递给表单选项。在树枝模板中渲染自定义formType选项

请参见下面的代码是我曾尝试:

这是我的控制器:

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

这是我formType:

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:我已经定义在实体

回答

1

public function __toString()未经测试的代码,您已经设置了现在的样子,你会被渲染一个选择元素。因此,对你进行循环播放没有任何意义。

您需要将属性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' 
       ) 
      )) 
+0

你分辩! 'code''expanded'=> true' code' but the error still here – Emaus

+0

You rigth! ''expanded'=> true'呈现小部件,'multiple'=> true'呈现为复选框 ,但错误不在块中。是在{{form_star(form)}}和'{{form_end(form)}}}中......我不知道为什么。 – Emaus

+0

你的意思是你仍然得到同样的错误?你是否可以在你的form_div_layout.html.twig特别是第277行显示错误代码,如果它是相同的错误。 – Medard