Symfony2 customizes form error messages

Could you please help me understand how to configure form error messages using Symfony2? I want to change the layout of HTML by adding div, class, etc.

Reading the manual, he gives a piece of code that is placed in a file called fields_errors.html.twig , but it does not indicate where to put this file, and if additional configuration is required.

Can someone help me?

+7
source share
3 answers

You must place the template in the Resourses/views/ folder of your package. For example,

 {# Vendor/YourBundle/Resourses/views/form_fields.html.twig #} {% extends 'form_div_layout.html.twig' %} {% block form_errors %} {# your form error template #} {% endblock form_errors %} {# other customized blocks #} 

And then in the form page template

 {% extends your:page:layout %} {% form_theme form 'VendorYourBundle::form_fields.html.twig' %} {{ form_errors(form.field) }} {# ..... #} 

For more help on options and implementations, enter a topic cookbook topic and default field layout implementation

+5
source

You can configure all your error messages at once in your template:

 <div class="your_new_class"> {{ form_errors(form) }} </div> 

Or individually (if your title field)

 <div class="your_new_class"> {{ form_errors(form.task) }} </div> 
+1
source

In symfony3, first call the theme form in config.yml

 twig: debug: "%kernel.debug%" strict_variables: "%kernel.debug%" form_themes: - 'YourBundle:FormTheme:error.html.twig' 

Twig error.html.twig example

 {% block form_errors %} {% spaceless %} {% if errors|length > 0 %} <div class="alert alert-danger"> {% for error in errors %} <strong>{{ error.message }}</strong> {% endfor %} </div> {% endif %} {% endspaceless %} {% endblock form_errors %} 
+1
source

All Articles