Learn how to print a list of all the errors of a submitted form with Twig in Symfony 4.

There's no doubt that the Twig helpers for rendering form widgets and errors are pretty easy to use and useful. However, they are usually displayed with a custom markup that we may not like when we work in some specific area of the project. Personally, i love to display all the errors of the form together in a simple list that will be shown to the user after the form has been submitted (and if there's an error of course). In Twig you can easily print the errors of a specific field using the form_errors helper or include it automatically during the rendering of the widget itself with form_row:

{# Displays global errors not specific to one field #}
{{ form_errors(form) }}

{# Displays errors specific to field #}
{{ form_errors(form.email) }}

{# Displays form_widget form_label and form_errors for field #}
{{ form_row(form.email) }} 

However, as mentioned for our needs, this isn't useful as the error will appear under every field, which for some designs is awful. There's an easier way to obtain the list of all the catched errors of the form (constraint failures) that can be shown to the user when the submitted information wasn't correct. The form variable that is sent to Twig from a controller in Symfony 4 contains the vars property, which contains multiple properties with information about the entity that is being used for the form, the current value, the method, the data and what's important for us, the errors of the form.

Check the following snippet that accomplishes the mentioned logic (replace MyFormVariable with your form variable of course):

{# For convenience sake of this snippet, store the errors in a variable #}
{% set formErrors = MyFormVariable.vars.errors.form.getErrors(true) %}
                                    
{# If there are errors in the form, display them in this unorganized list #}
{% if formErrors|length %}
    <ul>
        {% for error in formErrors %}
            <li>{{ error.message }}</li>
        {% endfor %}
    </ul>
{% endif %}

This short, but useful snippet will allow you to display all the errors of every field in the form in a simple list that can be just shown once to the user instead of forcing him to scroll down over the page to see which fields aren't valid.

Happy coding !


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