Customize Authentication - Login Symfony2 Messages

女生的网名这么多〃 提交于 2019-11-26 18:15:56

问题


So I'm reading the security chapter of Symfony2 Book. I understand everything, but I'd like to customize the error message if a there is a login error.

In which file can I change this?

This is the template:

{% if error %}
    <div>{{ error.message }}</div>
{% endif %}

<form action="{{ path('login_check') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />

<label for="password">Password:</label>
<input type="password" id="password" name="_password" />

{#
    If you want to control the URL the user is redirected to on success (more details below)
    <input type="hidden" name="_target_path" value="/account" />
#}

<input type="submit" name="login" />

I believe the worst way of doing this would be something like:

if (error.message=="Bad credentials")
    echo "Los datos son erróneos :)"

if (error.message==The presented password is invalid")
    echo "La combinación username/password no es correcta :)"

Would you help me please?


Edit: I got it working:

In case someone needs to do this, be sure you add this line to the config.yml

#app/config/config.yml
framework:
    translator: { fallback: en }

and put in the file messages.whateverisyourlanguage.yml, in my case messages.es.yml, lines like this one:

Text you want to translate : Translated text

#Foo\DummyBundle\Resources\translations\messages.es.yml
The presented password cannot be empty.: El campo contrasena no debe estar vacio
The presented password is invalid.: Los datos suministrados son incorrectos
Bad credentials: Los datos suministrados son incorrectos

Be careful with the text you want to translate. If the text has a dot at the end, you have to put the dot. I wasn't doing that and it wasn't working.

footranslate. is different than footranslate

Greetings! :)


回答1:


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 %}



回答2:


There is another possibility if you don't want to use translations. You can just replace the message, for example:

{{ error.message | replace({"Bad credentials." : "Invalid username or password."}) }}


来源:https://stackoverflow.com/questions/9201849/customize-authentication-login-symfony2-messages

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