Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

Information below shows us how we can handle form submission errors in different ways.


Hint


First of, dump form variable with {{ dump(form) }} to see how much information it gives us.


When error_bubbling is set to false


This is the default behaviour of form types for errors and used to handle/display errors individually in templates. There are three ways of handling errors which is shown below.


FormType


public function buildForm(FormBuilderInterface $builder, array $options = [])
{
$builder
->add('code', 'text', ['required' => false])
->add('name', 'text', ['required' => false]);
}

Twig


{% extends '::base.html.twig' %}

{% block body %}
{% spaceless %}
{{ form_start(form, {'method': 'POST', 'action': path('country_create')}) }}

{% if not form.vars.valid %}
<ul style="border: 1px solid red">
{% if form_errors(form.code) !='' %}<li>{{ form_errors(form.code)|striptags }}</li>{% endif %}
{% if form_errors(form.name) !='' %}<li>{{ form_errors(form.name)|striptags }}</li>{% endif %}
</ul>
{% endif %}

<ul style="border: 1px solid red">
{% if form.code.vars.errors|length != '' %}
<p>{{ form_errors(form.code)|striptags }}</p>
{% endif %}

{% if form.name.vars.errors|length != '' %}
<p>{{ form_errors(form.name)|striptags }}</p>
{% endif %}
</ul>

<ul style="border: 1px solid red">
<p>CODE: {{ form_widget(form.code) }}{{ form_errors(form.code) }}</p>
<p>NAME: {{ form_widget(form.name) }}{{ form_errors(form.name) }}</p>
</ul>

<p><button name="button">Submit</button></p>
{{ form_end(form) }}
{% endspaceless %}
{% endblock %}

Output



When error_bubbling is set to true


This is used to handle/display errors in one go but you can still handle them individually.


FormType


public function buildForm(FormBuilderInterface $builder, array $options = [])
{
$builder
->add('code', 'text', ['required' => false, 'error_bubbling' => true])
->add('name', 'text', ['required' => false, 'error_bubbling' => true]);
}

Twig


{% extends '::base.html.twig' %}

{% block body %}
{#{% spaceless %}#}
{{ form_start(form, {'method': 'POST', 'action': path('country_create')}) }}

{% if form_errors(form) != '' %}

<div style="border: 1px solid red">
{{ form_errors(form) }}
</div>

{% endif %}

{% if form.vars.errors is iterable %}
<div style="border: 1px solid red">
{% for error in form.vars.errors %}
<p>{{ error.origin.name ~ ':' ~ error.message }}</p>
{% endfor %}
</div>

{% endif %}

<ul style="border: 1px solid red">
<p>CODE: {{ form_widget(form.code) }}</p>
<p>NAME: {{ form_widget(form.name) }}</p>
</ul>

<p><button name="button">Submit</button></p>
{{ form_end(form) }}
{#{% endspaceless %}#}
{% endblock %}

Output