如何在 symfony2 表单集合中自定义数据原型?自定义、原型、表单、数据

2023-09-07 09:42:32 作者:笙歌绝丶何以笙箫默

我的表单中有一组隐藏字段.

I've got a collection of hidden fields in my form.

<ul id="user_roles">
  <li><hidden field value="role1"></li>
  <li><hidden field value="role2"></li>
  (...)
</ul>

我使用 jQuery(和数据原型)添加新角色.

I use jQuery (and data-prototype) to add new roles.

问题是我想渲染这样的东西:

<ul id="user_roles">
  <li>role1 <hidden field value="role1"></li>
  <li>role2 <hidden field value="role2"></li>
  (...)
</ul>

初始渲染没有问题:我只是放了:

{% for role in roles %}
 <li> {{ role }} {{ form_row(role) }} </li>
{% endfor %}

但默认数据原型将仅呈现 {{ form_row(role) }}(隐藏字段).

But the default data-prototype will render only {{ form_row(role) }} (a hidden field).

我应该在哪里更改默认数据原型?

Where am I supposed to change the default data-prototype?

form_div_layout.html 中没有我可以自定义的 {% block prototype %}....

There is no {% block prototype %} in form_div_layout.html that i could customize....

推荐答案

集合小部件定义如下:

{% block collection_widget %}
{% spaceless %}
    {% if prototype is defined %}
        {% set attr = attr|merge({'data-prototype': form_row(prototype) }) %}
    {% endif %}
    {{ block('form_widget') }}
{% endspaceless %}
{% endblock collection_widget %}

因此您可以覆盖它以控制您希望如何渲染原型.

So you can override this to gain control on how you want to rendre the prototype.