将变量注入扩展的树枝 form_theme

Inject variable into extended twig form_theme

我要创建一个动态表单,我想扩展一个小部件以便将其显示为 <tr>。 事实上,table 的每一列都是一个包含一些字段的动态组。

我想做的就是像这样遍历 myform_widget 中的组:

这里是tableheader

<table id="myforms-table" class="table">
    <thead>
    <tr>
        {% for group in groups %}<th>{{ group.label }}</th>{% endfor %}
    </tr>
    </thead>
    <tbody data-prototype="{{ form_widget(form.myforms.vars.prototype)|e }}">

    </tbody>
</table>

这是 myform 块:

{% block myform_widget %}
    <tr>

        {% for group in groups %}
            <td>
                {% for field in group.fields %}
                    {{ form_row( form.children.(field.codeField) ) }}
                {% endfor %}
            </td>
        {% endfor %}

    </tr>
{% endblock %}

我得到一个例外 Variable "groups" does not exist。 我假设 form_theme 无法访问 groups 变量,但我怎样才能访问它? 强文本 谢谢 o/

我找到了一个简单的解决方案。

在我的表单类型文件中,我添加了一个 groups 属性,就像这样:

public function buildView(FormView $view, FormInterface $form, array $options)
{
    $view->vars['groups'] =  $this->groups;
}

现在我可以使用 :

检索它
{% block partition_widget %}
    <tr>
        {% for group in form.vars.groups %}
            <td>
                {% for field in group.fields %}
                    {{ form_row(  attribute(form, field.codeField) ) }}
                {% endfor %}
            </td>
        {% endfor %}
    </tr>
{% endblock %}