Symfony2 customize form error messages

倾然丶 夕夏残阳落幕 提交于 2019-12-12 07:59:28

问题


can you please help me understand how to customize error messages in a form with Symfony2? I want to change the HTML layout, adding div, class, etc...

Reading the guide, it gives a piece of code to put in a file called fields_errors.html.twig but it doesn't tells where to put this file and if some extra configuration is needed.

Can somebody help me?


回答1:


You have to put the template in Resourses/views/ folder of your bundle. 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 your form page template,

{% extends your:page:layout %}

{% form_theme form  'VendorYourBundle::form_fields.html.twig' %}

 {{ form_errors(form.field) }}
 {# ..... #}

For more option and implementation reference check form theme cookbook entry and default field layout implementation




回答2:


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

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

Or individually (if your field is title for example)

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



回答3:


In symfony3 first call de 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 %}


来源:https://stackoverflow.com/questions/12121180/symfony2-customize-form-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!