1

我正在尝试在我的身份验证服务中设置带有 RedirectResponse 的 Flash 消息以进行登录。

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    if($request->isXmlHttpRequest()) {
        return JsonResponse::create([
            'status' => false,
            'message' => $exception->getMessage(),
            'callback' => 'Login.failed'
        ]);
    } else {
        $session = new Session();
        $session->getFlashBag()->set('error', $exception->getMessage());

        var_dump($session->getFlashBag()->all()); die; // Works here.

        return new RedirectResponse('/login');
    }
}

枝条:

{{ dump(app.session.flashbag.all) }}

{% for message in app.session.flashbag.get('error') %}
    <div class="alert alert-danger">{{ message|trans }}</div>
{% endfor %}

树枝模板中没有消息...

我想知道,redirectresponse 是否会刷新所有闪存消息?

4

2 回答 2

2

Symfony 无法神奇地获取所有 Session 实例并使用它。它只知道它自己创建的实例。那些住在Service Container中。您应该session从此容器中获取服务并使用它。

由于您可能在服务中,因此您应该使用以下内容更新您的服务定义:

services:
    your_service:
        class: ...
        arguments: ["@session"]

现在,更新您的类以将会话服务保存在属性中:

// ...
use Symfony\Component\HttpFoundation\Session\Session;

// ...
class YourClassName
{
    private $session;

    public function __construct(Session $session)
    {
        $this->session = $session;
    }
}

现在,改用保存在属性中的会话实例:

// ...
public function onAuthenticationFailure(...)
{
    // ...
    $this->session->getFlashBag()->set('error', ...);

    // ...
}
于 2015-04-19T11:01:06.150 回答
2

只是我解决了问题。调用后,{{ dump(app.session.flashbag.all) }}你的 flashbag 就变空了。

使用一次此代码:

{% for message in app.session.flashbag.get('error') %}
    <div class="alert alert-danger">{{ message|trans }}</div>
{% endfor %}

检查“如果……”不需要,或者您再次清空闪光灯袋,一切正常。

于 2015-12-04T10:29:06.760 回答