Customize Authentication - Login Symfony2 Messages
Solution 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 %}
Solution 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."}) }}
Comments
-
Francisco Ochoa almost 2 years
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 thanfootranslate
Greetings! :)
-
Francisco Ochoa about 12 yearsWell thanks. Now, where can I find all of the error messages a login form should throw? I believe I have to put exactly the message that will appear on the message file, so I could translate them all, but I'm not sure which messages are them.
-
jkucharovic about 12 yearsThere are only few messages – check out exception messages in files located in
./vendor/symfony/src/Symfony/Component/Security/Core/Authentication/Provider/
-
Francisco Ochoa almost 12 yearsThere are messages here too: vendor\symfony\src\Symfony\Component\Security\Core\User\UserChecker.php