How to check if form has errors in twig?

2019-06-21 18:52发布

问题:

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.)

回答1:

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 %}


回答2:

With symfony 3.4 it's not possible through form.vars.errors anymore except if you have error_bubbling = true and form compound = false which is unlikely.

You can either use a dirty code like this :

{% set errors = false %}
{% for child in form.children %}
        {% if child.vars.errors is defined and child.vars.errors|length %}
                {% set errors = true %}
        {% endif %}
{% endfor %}
{% if errors %}
        [...]
{% endif %}

If you are trying to build a login form with AuthenticationUtils, use a code like this in controller :

//Get the login error if there is one
if ($error = $authenticationUtils->getLastAuthenticationError()) {
        //Add error message to mail field
        $form->get('mail')->addError(new FormError($error->getMessageKey()));
}

//Last username entered by the user
if ($lastUsername = $authenticationUtils->getLastUsername()) {
        $form->get('mail')->setData($lastUsername);
}

//Render view
return $this->render('@ExampleBundle/template.html.twig', array('form' => $form->createView(), 'error' => $error));

And use a simple code like this in twig template :

{% if error %}
        [...]
{% endif %}