Beginner
Beginner

Reputation: 1030

How to show validation error message in front of each field in symfony2

I'm new to symfony and twig. I want to build my html forms using BootStrap CSS Framework. So my form looks like this in twig file:

<form action="{{ path('register')}}" class="form-horizontal span10 offset7" id="frmRegistration" method="POST"  {{ form_enctype(form) }} novalidate>
<fieldset>
    {{ form_widget(form._token) }}
    <div class="control-group">
        {{ form_label(form.userName, null, {'label_attr': {'class':'control-label'}})}}
        <div class="controls">
            {{ form_widget(form.userName, {'attr': {'data-path': path('ajax_user_exists') } }) }}
        </div>
    </div>
    <div class="control-group">
        {{ form_label(form.password.first, null, {'label_attr': {'class':'control-label'}})}}
        <div class="controls">
            {{ form_widget(form.password.first) }}
        </div>
    </div>
    <div class="control-group">
        {{ form_label(form.password.second, null, {'label_attr': {'class':'control-label'}})}}
        <div class="controls">
            {{ form_widget(form.password.second) }}
        </div>
    </div>

    <div class="control-group">            
        <div class="controls">
            <input id="register_submit" type="submit" value="تاييد" class="btn btn-primary" />
        </div>
    </div>     
</fieldset>

Now I want to show validation error messages exactly in front of each input. My problem is that how can I do this using twig? If I use {{ form_row(form.firstName) }} it will generate the label and input. But I cant wrap them inside the Bootstrap form structure. Any help is appreciated in advance.

UPDATE

Sorry for not being precise when reading symfony documentation. I found the solution. Using {{ form_errors(form.firstName) }} solved the problem.

Upvotes: 5

Views: 3713

Answers (1)

George
George

Reputation: 1489

This is still showing up as unanswered and thought it would be helpful if the answer was added at the end so this could be closed.

To add an error message on a form row, use:

{{ form_errors(form.firstName) }}

You will need to add the widget with this and the label if you want a label to show. Full rendering for each row requires all three:

{{ form_label(form.firstName) }}
{{ form_errors(form.firstName) }}
{{ form_widget(form.firstName) }}

Upvotes: 3

Related Questions