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.)
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.
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.
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.
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:
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With