Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the form_row behaviour in Symfony 2 / Twig

Tags:

twig

symfony

By default a form_row(form.name) is rendered as something like:

<div><label for="form_name" class=" required">Name</label><input type="text" id="form_name" name="form[name]" required="required" maxlength="45" value=""></div>

How/where can I change the behaviour of form_row() to for example:

<div class="someClassName"><label for="form_name" class=" required">Name</label></div><div class="someOtherClassName"><input type="text" id="form_name" name="form[name]" required="required" maxlength="45" value=""></div>
like image 816
Roel Veldhuizen Avatar asked Dec 06 '11 19:12

Roel Veldhuizen


1 Answers

You can check this URL: http://symfony.com/doc/2.0/cookbook/form/form_customization.html#cookbook-form-theming-methods

There's a paragraph about customizing form_row().

Here's a simple example. By default, form_row() would create a simple html structure like this:

TWIG:

{{ form_row(form.email, { 'label' : 'Your email address' }) }}

HTML:

<div>
    <label for="register_email" class=" required">Your email address</label>
    <input type="email" id="register_email" name="register[email]" required="required" />
</div>

So, according to the docs, you can create a new twig template, and add class="form_row" to surrounding the field and label. Place it in YourBundle/views/Form/fields.html.twig and put the following code in there:

{% block field_row %}
<div class="form_row">
    {{ form_label(form) }}
    {{ form_errors(form) }}
    {{ form_widget(form) }}
</div>
{% endblock field_row %}

In your template file, add the following line:

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

Now, the form_row template from that file you created will be used, and will return the following HTML code:

<div class="form_row">
    <label for="register_email" class=" required">Email</label>        
    <input type="email" id="register_email" name="register[email]" required="required" />
</div>

Hope that it helps.

like image 149
mkrowiarz Avatar answered Sep 24 '22 21:09

mkrowiarz