54

Since umpteens days, I block on a problem with Symfony 2 and forms.

I got a form of websites entities. "Websites" is a collection of website's entities and each website contains two attributes : "type" and "url".

If I want to add more of one website in my database, I can click on a "Add another website" link, which add another website row to my form. So when you click on the submit button, you can add one or X website(s) at the same time.

This process to add a row use the data-prototype attribute, which can generate the website sub-form.

The problem is that I customize my form to have a great graphic rendering... like that :

<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>

But the data-prototype doesn't care about this customization, with HTML and CSS tags & properties. I keep the Symfony rendering :

<div>
<label class=" required">$$name$$</label>
<div id="jobcast_profilebundle_websitestype_websites_$$name$$">
<div>
<label class=" required">Type</label>
<div id="jobcast_profilebundle_websitestype_websites_$$name$$_type">
<div>
<label for="jobcast_profilebundle_websitestype_websites_$$name$$_type_code" class=" required">label</label>
<select id="jobcast_profilebundle_websitestype_websites_$$name$$_type_code" name="jobcast_profilebundle_websitestype[websites][$$name$$][type][code]" required="required">
<option value="WEB-OTHER">Autre</option>
<option value="WEB-RSS">Flux RSS</option>
...
</select>
</div>
</div>
</div>
<div>
<label for="jobcast_profilebundle_websitestype_websites_$$name$$_url" class=" required">Adresse</label>
<input  type="url" id="jobcast_profilebundle_websitestype_websites_$$name$$_url" name="jobcast_profilebundle_websitestype[websites][$$name$$][url]" required="required" value="" />
</div>
</div>
</div>

Does anyone have an idea to make that hack ?

12 Answers 12

76

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

Sign up to request clarification or add additional context in comments.

8 Comments

Endfilter twig tag should end with one curly bracket, not two. @Jivan Can you edit it as we can't edit the post for just one character ?
Very helpful, thank you! Also, it might be common sense but do not include form_start and form_end functions in the twig template if you're going this route. I found out the hard way that including those causes issues with persisting to the database.
BTW: I tried to get a similar result with my included template like the original prototype provided. The escape filter does not remove the spaces neither the new rows: gist.github.com/webdevilopers/… I tried adding twig's spaceless but still the prototype data is not in a single row: gist.github.com/webdevilopers/…
Is it possible to get access to the index-varibale in the template?
Is this supposed to work also when entity already has items in the collection ? For me custom template is only appying to new entries
|
49

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

6 Comments

I can't for the life of me get this to function. Do you know if it's still valid for Symfony2.5?
This answer should be marked as best and simplest answer! Thanks!
I only get "Impossible to invoke a method ("widget_prototype") on a string variable ("SendisPresentationFrontendBundle:DeliverySlip:deliverySlipForm.html.twig")." Any suggestions what i can do about it?
@MaxSchindler Are you calling the macro from within the same file using _self.widget_prototype ?
This solution is working perfectly. Just note that as from Twig 2.0, using _self inside the data-prototype field can lead to a "can't invoke a method macroname on a string variable". To solve this, you just have to add {% import _self as whatevername %} and call whatevername.macroname in your template to make it work.
|
25

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' %}

2 Comments

The template is perfect to iterate on collections and render the all collection as you desire. Merci
Nice! I even worked out how to do this without duplicating code: gist.github.com/eikes/5788231
5

I've run into similar problem recently. Here's how you can override the collection prototype without having to explicitly set it in the html:

{% set customPrototype %}
    {% filter escape %}
        {% include 'AcmeBundle:Controller:customCollectionPrototype.html.twig' with { 'form': form.collection.vars.prototype } %}
    {% endfilter %}
{% endset %}
{{ form_label(form.collection) }}
{{ form_widget(form.collection, { 'attr': { 'data-prototype': customPrototype } }) }}

You can do whatever you want then in your custom twig. For example:

<div data-form-collection="item" data-form-collection-index="__name__" class="collection-item">
<div class="collection-box col-sm-10 col-sm-offset-2 padding-top-20">
    <div class="row form-horizontal form-group">
        <div class="col-sm-4">
            {{ form_label(form.field0) }}
            {{ form_widget(form.field0) }}
        </div>
        <div class="col-sm-3">
            {{ form_label(form.field1) }}
            {{ form_widget(form.field1) }}
        </div>
        <label class="col-sm-3 control-label text-right">
            <button data-form-collection="delete" class="btn btn-danger">
                <i class="fa fa-times collection-button-remove"></i>{{ 'form.collection.delete'|trans }}
            </button>
        </label>
    </div>
</div>

Useful when you only have to do it in specific places and don't need a global override that's applicable to all collections.

1 Comment

It might work for the manually added sub-form, but in my case it doesn't work with the sub-forms automatically created from the entities field (i.e. on update, if some elements of the collection already exist).
5

I know that answer is very late but it maybe useful for visitors.

on your theme file you can simply use one block for rendering every collection entry of websites widget as following:

{% block _jobcast_profilebundle_websitestype_websites_entry_widget %}
     <div class="informations_widget">{{ form_widget(form.type.code) }}</div>
     <div class="informations_error">{{ form_errors(form.type) }}</div>
     <div class="informations_widget">{{ form_widget(form.url) }}</div>
     <div class="informations_error">{{ form_errors(form.url) }}</div>
{% endblock %}

also create theme block for your collection widget row as following:

{% block _quiz_question_answers_row %}
     {% if prototype is defined %}
        {%- set attr = attr | merge({'data-prototype': form_row(prototype) }) -%}
    {% endif %}

     {{ form_errors(form) }}

     {% for child in form %}
         {{ form_row(child) }}
     {% endfor %}
{% endblock %}

now the prototype and the rendered collection entry will be the same.

Comments

2

I had a somewhat similar issue. You might have to tweak this to work for your case, but someone may find it helpful.

Create a new template file to hold your custom form 'theme'

./src/Company/TestBundle/Resources/views/Forms/fields.html.twig

Normally, you can use the form_row function to display a field's label, error, and widget. But in my case I just wanted to display the widget. As you say, using the data-prototype feature would also display the label, so in our new fields.html.twig type your custom code for how you want the field to look:

{% block form_row %}
{% spaceless %}
        {{ form_widget(form) }}
{% endspaceless %}
{% endblock form_row %}

I removed the container div, and the label and error, and just left the widget.

Now in the twig file that displays the form, simply add this after the {% extends ... %}

{% form_theme form 'CompanyTestBundle:Form:fields.html.twig' %}

And now the form_widget(form.yourVariable.var.prototype) will only render the field and nothing else.

Comments

1

Application wide form theming will be applied to the prototype. See Making Application-wide Customizations

Comments

1

Here is sample code for custom data-prototype:

{{ form_widget(form.emails.get('prototype')) | e }}

where emails — your collection.

1 Comment

How is it custom? Isn't it default data-prototype?
1

To customize differently existing collection items VS prototype, you can override collection_widget like this:

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

And then in your custom entry:

{% block _myCollection_entry_row %}

  {% if(inPrototype is defined) %}
      {# Something special only for prototype here #}
  {% endif %}
{% endblock %}

Comments

0

If you do not need to define a template system-wide, simply set a template in your twig template, and ask twig to use it.

{# using the profiler, you can find the block widget tested by twig #}
{% block my_block_widget %}
    <div >
      <p>My template for collection</p>
        <div >
          {{ form_row(form.field1)}}
        </div>
        <div>
          {{ form_row(form.field2)}}
        </div>
    </div>
{% endblock %}

{% form_theme form.my_collection _self %}

<button data-form-prototype="{{ form_widget(form.my_collection.vars.prototype) )|e }}" >Add a new entry</button>

Comments

0

There are two blocks that you can possibly target to add a custom theme to a collection field:

_myCollection_row and _myCollection_entry_row

_myCollection_row - renders the whole collection.

_myCollection_entry_row - renders a single item.

The prototype relies on _myCollection_entry_row so if you theme _myCollection_row only your theme will appear in the form, but not the prototype. The prototype uses _myCollection_entry_row.

So it's best to theme _myCollection_entry_row first, and then theme _myCollection_row only if required. BUT - if you theme _myCollection_row make sure it calls _myCollection_entry_row to render each item in your collection.

Comments

-1

This post focuses on using pre-existing conventions within the twig template.

Basing off "How to Embed a Collection of Forms" from the Symfony Cookbook (http://symfony.com/doc/master/cookbook/form/form_collections.html), you can just enter whatever html_escaped form data you wish in the data-prototype (maybe considered a hack, but works wonderfully) and only pages using that template will change.

In the example, they tell you to put:

    <ul class="tags" data-prototype="{{ form_widget(form.tags.vars.prototype)|e }}">
    ...
    </ul>

This can be successfully replaced with something such as:

<table class="tags" data-prototype="&lt;tr&gt;  &lt;td&gt;&lt;div&gt;&lt;input type=&quot;text&quot; id=&quot;task_tags__name__tagId&quot; name=&quot;task[tags][__name__][taskId]&quot; disabled=&quot;disabled&quot; required=&quot;required&quot;    size=&quot;10&quot; value=&quot;&quot; /&gt;&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;div&gt;&lt;input type=&quot;text&quot; id=&quot;task_tags__name__tagName&quot; name=&quot;task[tags[__name__][tagName]&quot; required=&quot;required&quot; value=&quot;&quot; /&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;">
    <tr>
        <th>Id</th>
        <th>Name</th>
    </tr>
    <tr>
    ...pre existing data here...
    </tr>
</table>    

Where the data-type attribute of the table with the class "tags" above is the html-escaped version (and line breaks removed though spaces are ok and required) of:

<tr>
    <td><div><input type="text" id="task_tags__name__tagId" name="task[tags][__name__][taskId]" disabled="disabled" required="required"    size="10" value="" /></div></td>
    <td><div><input type="text" id="task_tags__name__tagName" name="task[tags[__name__][tagName]" required="required" value="" /></div></td>
</tr>

...but you must also adjust the javascript in the example to add tr's instead of li elements:

function addTagForm(collectionHolder, $newLinkTr) {
    ...
    // Display the form in the page in an tr, before the "Add a question" link tr
    var $newFormTr = $('<tr></tr>').append(newForm);
    ...
};

...

// setup an "add a tag" link
var $addTagLink = $('<a href="#" class="add_tag_link">Add a tag</a>');
var $newLinkTr = $('<tr></tr>').append($addTagLink);

...

For me, the next step is figuring out how to define the prototype in an external file that I can somehow call in the twig template for the data-prototype that dynamically works with the form. Something like:

<table class="tags" data-prototype="{{somefunction('App\Bundle\Views\Entity\TagsPrototypeInTable')}}">

So if one of the other posts is describing this and I am too dense or if someone knows how to do such, say so!

There is a link to something from gitHub from Francois, but I didn't see any explanation so I think that is probably the more dynamic method I'll get to one of these near-future days.

Peace, Steve

Update:

One can also use just parts of the prototype:

data-prototype="&lt;tr&gt;  &lt;td&gt;{{ form_row(form.tags.vars.prototype.tagId) | e }}&lt;/td&gt; &lt;td&gt;{{ form_row(form.tags.vars.prototype.tagName) | e }}&lt;/td&gt;&lt;/tr&gt;"

Where the data-type attribute of the table with the class "tags" above is the html-escaped version (and line breaks removed though spaces are ok and required) of:

<td>{{ form_row(form.tags.vars.prototype.tagId) | e }}</td>
<td>{{ form_row(form.tags.vars.prototype.tagName) | e }}</td>

(I used http://www.htmlescape.net/htmlescape_tool.html.)

Symfony will replace the information between the {{}} with an html_escaped (because of the "|e") rendered field when the page is rendered. In this way, any customization at the field-level is not lost, but! you must manually add and remove fields to the prototype as you do so with the entity :)

1 Comment

Adding hardcoded form code in the prototype attribute defies the whole point of having the forms generated dynamically by Symfony. You don't want to have to update your prototype when you add or remove some fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.