Jon*_*ram 3 session symfony flash-message
我正在尝试第一次在Symfony2应用程序中设置然后显示flash消息.第一次显示时,不会清除正在设置的闪存消息.
我在控制器动作中设置了一条flash消息:
public function startAction()
{
if (!$this->hasError()) {
$this->get('session')->setFlash('test_start_error', '');
return $this->redirect($this->generateUrl('app', array(), true));
}
}
Run Code Online (Sandbox Code Playgroud)
在相应的视图中,如果设置了相关的闪存键,则会显示错误通知:
{% if app.session.hasFlash('test_start_error') %}
error content here
{% endif %}
Run Code Online (Sandbox Code Playgroud)
在正确的错误条件下,控制器设置flash消息,并在视图中显示相关的错误内容.
一旦显示,就会在请求后再次呈现闪存消息请求.通过检查相关会话数据var_dump($this->get('session')->getFlashBag());显示闪存内容保留在会话中.
我的印象是,已经显示一次的flash消息从会话中删除.这种情况不会发生在我身上.
显然我做错了什么 - 它是什么?
app.session.hasFlash('test_start_error')
Run Code Online (Sandbox Code Playgroud)
这实际上并没有破坏flash消息,下一部分也是如此
{{ app.session.flash('test_start_error') }}
Run Code Online (Sandbox Code Playgroud)
换句话说,你需要实际使用flash消息,而不是它将被销毁.你刚检查它是否存在.
编辑:根据thecatontheflat请求,这里是FlashBag(Symfony> 2.0.x)类的相应方法.
"有"方法:
public function has($type)
{
return array_key_exists($type, $this->flashes) && $this->flashes[$type];
}
Run Code Online (Sandbox Code Playgroud)
实际的get方法:
public function get($type, array $default = array())
{
if (!$this->has($type)) {
return $default;
}
$return = $this->flashes[$type];
unset($this->flashes[$type]);
return $return;
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它只会在您请求实际的Flash消息时取消设置会话,而不是在您检查其存在时.
在Symfony 2.0.x中,闪存行为是不同的.对于一个请求,闪烁字面意义是否持续使用或不使用.或者至少在浏览代码并在本地测试之后我就会有这种印象.
EDIT2:
哦,是的,你的情况下的实际sollution,如果现在不明显,是在if语句中使用removeFlash,如下所示:
{% if app.session.hasFlash('test_start_error') %}
error content here
{{ app.session.removeFlash('test_start_error') }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
感谢thecatontheflat,为了重新发送我,我实际上没有为给定的问题提供解决方案.:)
PS removeVlash方法在v2.1中已弃用,将从v2.3中删除.无论如何,如果你查看Session类,你可以看到它只是像中间人一样从FlashBag类调用get方法,并且该方法实际上执行了删除.