2016-11-28 129 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