自定义身份验证 - 登录Symfony2消息

Fra*_*hoa 19 customization login messages symfony

所以我正在阅读Symfony2 Book的安全章节.我理解一切,但如果有登录错误,我想自定义错误消息.

我可以在哪个文件中更改此内容?

这是模板:

{% 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" />
Run Code Online (Sandbox Code Playgroud)

我相信这样做的最糟糕方式是:

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 :)"
Run Code Online (Sandbox Code Playgroud)

你能帮帮我吗?


编辑:我搞定了:

如果有人需要这样做,请确保将此行添加到config.yml

#app/config/config.yml
framework:
    translator: { fallback: en }
Run Code Online (Sandbox Code Playgroud)

并将文件message.whateverisyourlanguage.yml放入,在我的例子中就是messages.es.yml,这样的行:

要翻译的文字:翻译文本

#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
Run Code Online (Sandbox Code Playgroud)

小心要翻译的文本.如果文本末尾有一个点,则必须放置点.我没有这样做而且没有用.

footranslate. 不同于 footranslate

问候!:)

jku*_*vic 16

你可以使用翻译.在parameters.ini 设置语言环境到您的语言并创建消息文件.然后在twig模板中使用:

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

  • 只有几条消息 - 查看位于`./ vendor/symfony/src/Symfony/Component/Security/Core/Authentication/Provider /中的文件中的异常消息. (2认同)

jpb*_*ter 5

如果您不想使用翻译,还有另一种可能性。您可以只替换消息,例如:

{{ error.message | replace({"Bad credentials." : "Invalid username or password."}) }}
Run Code Online (Sandbox Code Playgroud)