Symfony & FOSUserBundle. Customize validation errors on register template

孤街浪徒 提交于 2019-12-06 07:37:04

You will have to override the default symfony form error block. You can find out how to do it in the symfony documentation

you will be able to set this form theme globaly or per view as shown in the documentation

So for example if you would like to display the errors inside a div with a class alert alert-danger you would create a file views/Form/form_errors.html.twig

{% form_theme form _self %}

{# form_errors.html.twig #}
{% block form_errors %}
    {% spaceless %}
        {% if errors|length > 0 %}
        <div class='alert alert-danger'>
            {% for error in errors %}
                <div>{{ error.message }}</div>
            {% endfor %}
        </div>
        {% endif %}
    {% endspaceless %}
{% endblock form_errors %}

and to use this custom theme just in the registration form you would call at the top of your override file register_content.html.twig

{% form_theme form 'Form/form_errors.html.twig' %}

I found the solution. I have change the {{ form_error }} variable in Twig for form.field.vars.errors.

An example, If you want to customize your email validation errors:

<div>
    {{ form_errors(form.email) }}
</div>

change it by:

{% for errorItem in form.email.vars.errors %}
    <div>{{ errorItem.message }}</div>
{% endfor %}

You could use a div tag or whatever tag you want.

You can use translation. In parameters.ini set locale to your language and create message file. Then in twig template use:

    {% if error %}
        <div class="error">{{ error.message|trans({},'messages') }}</div>
    {% endif %}

Another solution would be:

{{ error.message | replace({"Bad credentials." : "Invalid username or password."}) }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!