CakePHP:检查是否设置了SPECIFIC flash消息


CakePHP: Check if SPECIFIC flash message is set

我有一个页面,其中有几个部分包含从同一页面提交的表单。表单会折叠以节省空间,但如果提交时出现错误,我希望有条件地保持它们的打开状态。

在我的控制器中,我为每个表单设置了一个特定的"键"(请参见下面的location_key),这使我能够在它们各自的位置进行回声:

控制器内:

$this->Session->setFlash('You missed something...', 'element_name', array('class'=>'error'), 'location_key');

视图:

$this->Session->flash('location_key')

我正在想办法检查$this->Session->flash('location_key')是否存在。如果我这样做,它工作,但取消设置闪烁消息:

if ( $this->Session->flash('location_key') ) // = TRUE
    //Do something
$this->Session->flash('location_key') // = FALSE (because it just got called)

如何在不导致此闪烁消息消失的情况下测试其存在?

想明白了!这项工作:

$this->Session->check('Message.location_key')

它返回真/假,这取决于是否设置了任何此类闪存消息。->read()也做同样的事情,但如果有,则返回闪存数据(关键的是,它会留下会话var,以便稍后仍能进行响应)。

Flash消息(意外)存储在会话中:

public function setFlash($message, $element = 'default', $params = array(), $key = 'flash') {
    CakeSession::write('Message.' . $key, compact('message', 'element', 'params'));
}

要测试是否存在闪烁消息,请测试会话中的等效密钥,例如:

if (CakeSession::check('Message.location_key')) {
    ...
}

根据api,在执行$this->Session->flash('location_key')时,SessionHelper会返回一个字符串(带有flash消息和元素),为什么不将该字符串存储到变量中呢?

$myFlash = $this->Session->flash('location_key');
if ($myFlash)
   /*etc*/
echo $myFlash;