In Symfony 4, when you do something like that:
<div>
{{ form_label(form.something) }}
{{ form_errors(form.something) }}
{{ form_widget(form.something) }}
</div>
The following is shown:
<div>
<label for="form_something">Something</label>
<ul>
<li>This field is required</li>
<li>Another error</li>
</ul>
<input type="text" id="form_something" name="form[something]" />
</div>
I would like to be able to customize the way in which errors are displayed.
Instead of being shown this way:
<ul>
<li>This field is required</li>
<li>Another error</li>
</ul>
I would like it to be this way:
<div class="form-control-feedback">This field is required</div>
<div class="form-control-feedback">Another error</div>
Y read this page How to Customize Form Rendering but I can not understand how it works.
Any idea? Thanks.
The documentation describes how you can configure errors output globally
You render it using
{% form_theme form 'form/form_errors.html.twig' %}
{# ... #}
{{ form_errors(form.something) }}
File form/form_errors.html.twig
{% block form_errors %}
{% spaceless %}
{% for error in errors %}
<div class="form-control-feedback">{{ error.message }}</div>
{% endfor %}
{% endspaceless %}
{% endblock %}
You can do this:
<div class="form">
<label class="control-label">{{ form_label(form.something) }}</label>
{{ form_widget(form.something, { 'attr': {'class' : 'form-control'}}) }}
{% if form.something.vars['errors']|length > 0 %}
<ul class="message">
{% for error in form.something.vars['errors'] %}
<li>{{ error.message }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
Review the entire code, you will find some answers for your questions.
Each properties or fields of a form has a vars attribute, this store some data, including the ['errors'] which contains all errors after you submit the form. You can retrieve this data and show the error separately.
The link Form Rendering Customization is related to how to customize the templates of the forms in your system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With