我第一次尝试在 Symfony2 应用程序中设置并显示 Flash 消息。所设置的闪现消息一旦显示就不会被清除。
我在 Controller 操作中设置了一条 Flash 消息:
public function startAction()
{
if (!$this->hasError()) {
$this->get('session')->setFlash('test_start_error', '');
return $this->redirect($this->generateUrl('app', array(), true));
}
}
如果设置了相关的闪存键,我会在相应的 View 中显示错误通知:
{% if app.session.hasFlash('test_start_error') %}
error content here
{% endif %}
在正确的错误条件下, Controller 设置闪现消息,并在 View 中呈现相关错误内容。
一旦显示,闪现消息就会在请求后再次出现。通过var_dump($this->get('session')->getFlashBag());
检查相关 session 数据。显示 Flash 内容保留在 session 中。
我的印象是,一条闪现消息显示过一次后,就从 session 中删除了。这不会发生在我身上。
显然我做错了什么 - 是什么?
最佳答案
app.session.hasFlash('test_start_error')
这实际上并不会破坏 Flash 消息,下一部分会破坏
{{ app.session.flash('test_start_error') }}
换句话来说,你需要实际使用flash message,否则它就会被销毁。您刚刚检查了它是否存在。
编辑:根据 thecatontheflat 请求,以下是来自 FlashBag 的相应方法。 (Symfony > 2.0.x) 类。
“有”方法:
public function has($type)
{
return array_key_exists($type, $this->flashes) && $this->flashes[$type];
}
实际的获取方法:
public function get($type, array $default = array())
{
if (!$this->has($type)) {
return $default;
}
$return = $this->flashes[$type];
unset($this->flashes[$type]);
return $return;
}
正如您所看到的,它仅在您请求实际的 Flash 消息时(而不是在您检查其存在时)取消 session 设置。
在 Symfony 2.0.x 中,flash 行为有所不同。闪光灯实际上只持续一次请求,无论是否使用。或者至少在浏览 the code 后我有这样的印象,并在本地进行测试。
编辑2:
哦,是的,您的情况的实际解决方案(如果现在还不明显)是在 if 语句中使用removeFlash,如下所示:
{% if app.session.hasFlash('test_start_error') %}
error content here
{{ app.session.removeFlash('test_start_error') }}
{% endif %}
感谢 thecatontheflat,让我知道我实际上还没有为给定的问题提供解决方案。 :)
附注removeFlash 方法在 v2.1 中已弃用,并将从 v2.3 中删除。无论如何,如果你查看 Session 类的内部,你会发现它只是充当从 FlashBag 类调用 get 方法的中间人,并且该方法实际上执行删除操作。
关于session - Symfony2 Flash 消息未清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12019162/