Custom collection templates in symfony2

2019-03-09 14:53发布

问题:

Is it posible to add custom global templates for items in collection form fields?

I don't want to customize the collection template itself, but the rendering of each object in the collection, for example for adding a specific class or markup to each object contained in the collection.

I have a form with a collection field added like this:

$builder
    ->add('items', 'collection', array(
        'type' => new ItemType(),
        'allow_add' => true,
        'allow_delete' => true,
        'prototype' => true
    ));

I want to define a twig template to add a "delete" button to each item in the collection (among other things).

I have found there is a 'collection_widget' template to customize collections, buy this is only for the collection itself, not individual items.

NOTE 1: I need to use a global template in order to do this for all collections in all forms, I know I can solve this for each form template, but that's not the point.

NOTE 2: So far I solved this with jquery, adding a class to collection_widget and adding buttons for all it's children with jquery. This works fine for now, but I'm looking for a 100% template solution, without having to do all the jquery handling. Ideally this should also work with the row prototype for adding new items.

回答1:

Finally I found a good solution to this. First, I had to create a collection_widget custom template (copied from the generic form_widget) and inside, instead of calling the form_rows block, I call collection_rows block, which is a customization of form_rows block. Inside the collection_rows block you can customize whatever you want, I just added a custom class for each child.

Here's the two templates:

{% block collection_widget %}
{% spaceless %}
    <div {{ block('widget_container_attributes') }}>
        {{ block('collection_rows') }}
        {{ form_rest(form) }}
    </div>
{% endspaceless %}
{% endblock collection_widget %}

{% block collection_rows %}
{% spaceless %}
    {{ form_errors(form) }}
    {% for child in form %}
        {{ form_row(child, {'attr':{'class':'collection-item'}}) }}
    {% endfor %}
{% endspaceless %}
{% endblock collection_rows %}


标签: php symfony twig