Test the validity of a Symfony form inside a Twig template
Published on 2019-07-23 • Modified on 2019-11-08
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.
[2019-11-08]: You can also use form.vars.submitted
to check is the form was submitted. In general, it only makes sense to test the validity status if the form was submitted.
{% if form.vars.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') }}
</div>
{% endif %}
More on Stackoverflow Random snippet