1

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.

2 Answers 2

1

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) }}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! You are right! Answer was just beneath my eyes... Thank you very much!
0

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

Comments

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.