Customize Authentication - Login Symfony2 Messages

Francisco Ochoa picture Francisco Ochoa · Feb 8, 2012 · Viewed 19.7k times · Source

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! :)

Answer

jkucharovic picture jkucharovic · Feb 9, 2012

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