Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if form has errors in twig?

Beside the form field specific error messages directly attached to the form field I would like to display a message above the form that the form contains errors.

How can I check in a Symfony3 twig template if a form has errors? There used to be something like this in Symfony2:

{% if form.get('errors') is not empty %}
    <div class="error">Your form has errors. Please check fields below.</div>
{% endif %}

But this doesn't work in Symfony3. Any ideas? (form.vars.errors doesn't work.)

like image 338
Gottlieb Notschnabel Avatar asked Jan 23 '16 17:01

Gottlieb Notschnabel


People also ask

How to list all errors of a form in twig view?

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.

How do I run a test in twig?

Tests can be executed by using the is operator in Twig to create a condition. Read the Twig documentation for more information. This test will check if the current choice is equal to the selected_value or if the current choice is in the array (when selected_value is an array). For a full list of variables, see: Form Variables Reference.

Are twig helpers for rendering form widgets and errors useful?

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.

What is the final argument in a twig function?

In almost every Twig function above, the final argument is an array of "variables" that are used when rendering that one part of the form. For example, the following would render the "widget" for a field and modify its attributes to include a special class:


1 Answers

Use form.vars.errors:

{% if form.vars.errors is not empty %}
    {# ... #}
{% endif %}

Attention! Note that this just evaluatues to true, if your root form has errors (or if child forms have errors and allow bubbling the error up to the root form). If regular child elements of your form have errors, this will not evaluate to empty!

So the valid variable is probably of more suitable:

{% if not form.vars.valid %}
    {# ... errors ! #}
{% endif %}
like image 147
Wouter J Avatar answered Oct 15 '22 19:10

Wouter J