I recently started using Symfony2 framework.
I already apologize for any incorrect terminology I will be using.
I would like to customize how forms are presented in my application.
More specifically, in my Twig file I am rendering the entire form with
{{ form(forms) }}
I would like to customize the layout of the form. I know that each row of the form can be expanded as
{{ form_start(forms) }}
//...
<div>
{{ form_label(forms.field) }}
{{ form_errors(forms.field) }}
{{ form_widget(forms.field) }}
</div>
//...
{{ form_end(forms) }}
With the form written in this format I could add the needed customization to the layout.
Here is the problem: my form does not have a pre-defined number of rows, but these depend on some values stored in the database. What I would like to do in my Twig is something like this
{{ form_start(forms) }}
{% for field in forms %}
<div>
{{ form_label(forms.field) }}
{{ form_errors(forms.field) }}
{{ form_widget(forms.field) }}
</div>
{% endfor %}
{{ form_end(forms) }}
Unfortunately, this for loop does not work. I also looked into ( How to Customize Form Rendering ), but I think this does not suit my case (does it?).
Any suggestion?
Thank you in advance for your help.
You need to customize form_row method http://symfony.com/doc/current/cookbook/form/form_customization.html#customizing-the-form-row
// my_form.html.twig
{% extends 'form_div_layout.html.twig' %}
{% block form_row %}
<div>
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock form_row %}
// view.html.twig
{% form_theme form 'my_form.html.twig' %}
{{ form_start(form) }}
As a more flexible solution, you can do what you want directly without changing the way all form rows on the form are themed together.
Assuming your main form contains a Collection (if not, let us now how it's done!) called subforms
with a variable number of items in (each of which is another form), you can do something like this:
{{ form_start(forms) }}
{% for subform in forms.subforms %}
<div>
{{ form_label(subform.fieldname) }}
{{ form_errors(subform.fieldname) }}
{{ form_widget(subform.fieldname) }}
</div>
{% endfor %}
{{ form_end(forms) }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.