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
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉