Symfony Twig customize an Individual field for a collection

In the documentation there is a way in Symfony to customize a Individual field, based on the name/id of the widget.

{% form_theme form _self %}

{% block _product_name_widget %}
    <div class="text_widget">
        {{ block('field_widget') }}
    </div>
{% endblock %}

{{ form_widget(form.name) }}

Here, the _product_name_widget fragment defines the template to use for the field whose id is product_name (and name is product[name]).

This works for a normal widget, but not if a widget is inside a collection. Because of the extra columns. Like this:

name="productbundle_product_type[foobar][1][value]" id="productbundle_product_type_foobar_1_value"

What is the way to make the Twig customization work inside the collection?

I thought something like this, but that doesn't work:

{% for db in edit_form.list %}
    {% block _productbundle_product_type_foobar_{{ db.name }}_widget %}
        <div class="text_widget">
            {{ block('field_widget') }}
        </div>
    {% endblock %}
{% endfor %}

Even the following doesn't work:

{% _productbundle_product_type_foobar_1_value_widget %}

What is the way to make it work?


我几天前正在做一个项目,遇到了这个问题 - 我找到的解决方案是一对看起来像这样的块(剥离了项目特定的代码):

{# Collection markup #}
{% block my_collection_widget %}
    {# Customise collection row prototype for allow_add #}
    {% if prototype is defined %}
        {% set data_prototype = block('my_collection_item_widget')  %}
        <div id="my_prototype" data-prototype="{{ data_prototype }}" style="display: none"></div>
    {% endif %}

    {% for prototype in form %}
        {{ block('my_collection_item_widget') }}
    {% endfor %}
{% endblock my_collection_widget %}

{# Collection row markup #}
{% block my_collection_item_widget %}
    {# Collection contains simple, single type #}
    {{ form_errors(prototype) }}
    {{ form_label(prototype) }}
    {{ form_widget(prototype) }}

    {# OR #}

    {# Collection contains a compound type, render child types independantly #}
    {{ form_errors(prototype.inner_widget) }}
    {{ form_label(prototype.inner_widget) }}
    {{ form_widget(prototype.inner_widget) }}
{% endblock my_collection_item_widget %}
链接地址: http://www.djcxy.com/p/14288.html

上一篇: 用同一类的另一个片段替换片段

下一篇: Symfony Twig为一个集合定制一个Individual字段