Test the validity of a Symfony form inside a Twig template

Published on 2019-07-23 • Modified on 2019-07-23

Sometimes it's useful to know if a form is valid inside a Twig template. Indeed, when using the form_ helpers like form_error all is automatic and you don't know the form's validity status. This is a snippet I am using in this blog post. Submit the form to see the result! As you can see, in this case it allows me to assign some special CSS classes and to display the right message to the user.

{% if submitted %}
    {% set class = form.vars.valid ? 'success' : 'warning' %}
    <div class="h4 alert alert-{{ class }}">
        {{ (form.vars.valid ? 'form2_valid' : 'form2_not_valid')|trans({}, 'post_26') }}
{% endif %}

 More on Stackoverflow

» Comments

Privacy-focused with Commento. (Comment system added on 2019-10-17: be the first! 🥇)