Learn how to display all the errors of a form with Twig.

Thanks to Twig, now the templating with Symfony is really easy to handle and understand. However, the documentation of symfony doesn't clear a lot of basics tasks that you probably don't know how to solve instantly.

In this case, we'll show how to get and display the errors of forms in Symfony 3.

Twig

List all errors in the form

To list all the errors of a form in a twig view, you'll need to check first if it has errors checking for form.vars.valid property. Then, loop through every form children and print all the errors on it.

{# 
If the form is not valid then :
Note: in this case the form variable is : form
 #}
{% if not form.vars.valid %}
<ul>
    {# Loop through every form item #}
    {% for child in form.children %}
        {# Display the errors of the form item #}
        {%for error in child.vars.errors%}
            <li>{{error.message}}</li>
        {%endfor%}
    {%endfor%}
</ul>
{%endif%}

Single item error

If you still want to display the errors next to the form item, you need to use the form_errors tag which will display the error related to that form item.

{{ form_start(form) }}

    <div>
        {{ form_widget(form.subject) }}
        {{ form_errors(form.subject) }}
    </div>
    <div>
        {{ form_widget(form.name) }}
        {{ form_errors(form.name) }}
    </div>
    <div>
        {{ form_widget(form.email) }}
        {{ form_errors(form.email) }}
    </div>
    <div>
        {{ form_widget(form.message) }}
        {{ form_errors(form.message) }}
    </div>
    
    <input type="submit" value="Submit">
    
{{ form_end(form) }}

In this case, when the form is submitted and the form is invalid according to its constraints in the FormType, then you'll see the error message of every input down of it.

Invalid form twig symfony 3

Controller (PHP)

To get all the errors of a form with PHP, you can use the getErrors method, which can be called directly in a form or a form item.

<?php

$form = ...;

// ...

// a FormErrorIterator instance, but only errors attached to this
// form level (e.g. "global errors)
$errors = $form->getErrors();

// a FormErrorIterator instance, but only errors attached to the
// "subject" field
$errors = $form['subject']->getErrors();

// a FormErrorIterator instance in a flattened structure
// use getOrigin() to determine the form causing the error
$errors = $form->getErrors(true);

// a FormErrorIterator instance representing the form tree structure
$errors = $form->getErrors(true, false);

You can choose for this option if you prefer PHP instead of Twig or you want to wrap all your information in the controller and then render it in the view.

Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors