如何在Symfony2中多次呈现相同的表单?

如何在Symfony2中多次呈现相同的表单?

问题描述:

我有一个包含多个购物车的模板。可以有不定数量的推车,没有固定的限制。如何在Symfony2中多次呈现相同的表单?

在每个购物车中,我想要一个表单,用户可以选择一个国家。如果他提交表格,应该确定运输成本。

现在我做以下,以实现它在树枝:

{% for cart in carts %} 
    {# Some template stuff #} 
    {{ form_start(form) }} 
     <div class="form-input"> 
     <label for="country" class="middle-color">Country <span class="active-color">*</span></label> 
     {{ form_widget(form.country) }} 
    {{ form_end(form) }} 
{% endfor %} 

这是我的表单生成器:

$form = $this->createFormBuilder() 
    ->add('country', 'choice', array('choice_list' => $choiceList, 'label' => 'country', 
     'attr' => array('class' => "custom-selectbox dark-color light-gradient"))) 
    ->getForm(); 

现在的问题是,这种逻辑正常工作的第一台车,但没有任何形式显示给其他购物车。我该如何处理这个问题?

您应该使用collection表单类型。这里是一个指南开始How to Embed a Collection of Forms

P.S.请注意,渲染表单窗口小部件后,表单组件将其标记为呈现状态,并且不再呈现。

+0

我看不出这会帮助我。我创建一个choice_list取决于外部数据。我不想多次显示choice_list,而是整个表单 – KhorneHoly

我遇到了这个问题和关于类似问题的另一个问题。 You can find my first answer for a solution here

为了把它包起来,我没有在控制器窗体上调用createView()函数,就像通常在将窗体传递给视图时一样,但是在树枝视图本身中。

E.g.在你的控制器动作你做的形式返回对象本身:

return $this->render('AppBundle:Cart:list.html.twig', ['formObject' => $form]; 

,并在你看来,你会设置的形式,每个循环:

{% for cart in carts %} 
    {# Some template stuff #} 
    {% set form = formObject.createView %} 
    {{ form_start(form) }} 
     <div class="form-input"> 
     <label for="country" class="middle-color">Country <span class="active-color">*</span></label> 
     {{ form_widget(form.country) }} 
    {{ form_end(form) }} 
{% endfor %}