【问题标题】:How to render same form multiple times in Symfony2?如何在 Symfony2 中多次渲染相同的表单?
【发布时间】:2015-07-10 09:35:12
【问题描述】:

我有一个包含多个购物车的模板。购物车的数量可以是可变的,没有固定的限制。

在每个购物车中,我都希望有一个用户可以选择国家/地区的表单。如果他提交表格,则应确定运费。

现在我正在执行以下操作以在 twig 中实现它:

{% 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();

现在的问题是,这个逻辑对第一个购物车运行良好,但没有显示其他购物车的表单。我该如何处理?

【问题讨论】:

    标签: php forms symfony


    【解决方案1】:

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

    总结一下,我没有在控制器中的表单上调用createView() 函数,就像通常在将表单传递给视图时所做的那样,而是在树枝视图本身中调用。

    例如在您的控制器操作中,您确实返回了表单对象本身:

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

    【讨论】:

    • {% set form = formObject.createView %} 抛出错误Array to string conversion。你有Symfony 5.* 的解决方案吗?
    【解决方案2】:

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

    附:请注意,在渲染表单小部件后,表单组件会将其标记为已渲染并且不会再次渲染。

    【讨论】:

    • 我不明白这对我有什么帮助。我根据外部数据创建了一个choice_list。我不想多次显示choice_list,而是多次显示整个表单
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多