How to customize the data-prototype attribute in Symfony 2 forms How to customize the data-prototype attribute in Symfony 2 forms symfony symfony

How to customize the data-prototype attribute in Symfony 2 forms


A bit old, but here is a deadly simple solution.

The idea is simply to render the collection items through a Twig template, so you have full ability to customize the prototype that will be placed in your data-prototype="..." tag. Just as if it was a normal, usual form.

In yourMainForm.html.twig:

<div id="collectionContainer"     data-prototype="         {% filter escape %}             {{ include('MyBundle:MyViewsDirectory:prototype.html.twig', { 'form': form.myForm.vars.prototype }) }}         {% endfilter %}"></div>

And in MyBundle:MyViewsDirectory:prototype.html.twig:

<div>    <!-- customize as you wish -->    {{ form_label(form.field1) }}    {{ form_widget(form.field1) }}    {{ form_label(form.field2) }}    {{ form_widget(form.field2) }}</div>

Credit: adapted from https://gist.github.com/tobalgists/4032213


I know this question is quite old, but I had the same problem and this is how I soved it. I'm using a twig macro to accomplish this. Macros are like functions, you can render them with different arguments.

{% macro information_prototype(website) %}    <div class="informations_widget">{{ form_widget(website.type.code) }}</div>    <div class="informations_error">{{ form_errors(website.type) }}</div>    <div class="informations_widget">{{ form_widget(website.url) }}</div>    <div class="informations_error">{{ form_errors(website.url) }}</div>{% endmacro %}

now you can render this macro wherever you want. Note that information_prototype() is just the name of the macro, you can name it whatever you want. If you want to use the macro to render the given items and the prototype the same way, do something like this:

<div class="collection" data-prototype="{{ _self.information_prototype(form.websites.vars.prototype)|e }}">    {% for website in form.websites %}        {{ _self.information_prototype(website) }}    {% endfor %}    <button class="add-collection">Add Information</button></div>

form.websites.vars.prototype holds the prototype data of the form with the prototype_name you specified. Use _self.+macroname if you want to use the macro in the same template.

You can find out more about macros in the Twig documentation


You probably have found out since but here is the solution for others.

Create a new template and copy/paste this code in it:https://gist.github.com/1294186

Then in the template containing the form you want to customise, apply it to your form by doing this:

{% form_theme form 'YourBundle:Deal:Theme/_field-prototype.html.twig' %}