| #Symfony2, #forms, #twig

Custom form collection prototype in Symfony2

In this article I'll show how to use the twig macro tag to render a custom form collection item template.

This article assumes that you are familiar with the basic concept of the Symfony2 form collection prototype.

To render existing form collection items in the same way as the prototype, a twig macro is used. Twig macros are similar to functions in php. They can be called with different arguments. In this example, tagCollectionItem() is used, to render both the existing tags and the prototype. This way redundancy can be avoided and changes to the tag template automatically apply for the prototype and the existing form collection items.

{% macro tagCollectionItem(formData) %}
    <div class="name">{{ form_widget(formData.name) }}</div>
    <div class="published">{{ form_errors(formDate.published) }}</div>
{% endmacro %}

<div class="tags" data-prototype="{{ _self.tagCollectionItem(form.tags.vars.prototype)|e }}">
    {% for tag in form.tags %}
        {{ _self.tagCollectionItem(tag) }}
    {% endfor %}
    <button class="add-collection">Add Tag</button>
</div>

Here the macro is called using _self. because the macro is in the same file. Importing macros from other files is also possible, more information and use cases about macros in the twig documentation. This also works for nested form collections.

← Alfred2 special characters and keyboard shortcuts extension
→ How to call jQuery plugins using the apply() or call() functions