php - How to check if a Flash message exists in CakePHP 3?
问题描述
In Yii (both version) for flash messages we have methods like: hasFlash
for checking if a flash message exists beforehand and getFlash
to get the content of a specific flash message...
In Yii 1x I would say something like this (whether in the Controller or in a View):
View:
<?php if(Yii::app()->user->hasFlash('success')): ?>
<div class="alert alert-success">
<?=Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>
Controller:
if($something->happend()) {
Yii::app()->user->setFlash('success', 'You\'ve done something wonderful.');
return $this->redirect('/elsewhere');
}
In CakePHP 3 this seems impossible, since the only thing I can do is to set a Flash message:
$this->Flash->set('Welcome, to the real world.', [
'element' => 'success',
]);
There are no get
or has
methods for Flash messages, or anything similar that I could find related to FlashComponent and FlashHelper classes.
The other thing about this Flash messages implementation in CakePHP 3 is the way you render and show them to the visitor; you just say the following in your views/layout:
<?= $this->Flash->render(); ?>
That method will actually do the rendering, checking if a flash exists, whatever... and the thing is I need to check if a Flash message is sent/exists, then to do something else within the layout. Now it seems impossible to me or I am not looking in the right direction.
I would note that this is a very strange and bad implementation of Flash messages in CakePHP 3...
Finally, the question:
How can I check if a Flash message exists, whether in a view or in a controller?
解决方案
有关设置 Flash 消息的文档说消息存储在会话中。更具体地说,它说:
FlashComponent 的 __call() 和 set() 方法可选地接受第二个参数,一个选项数组:
- 键默认为“闪光”。在会话中 Flash 键下找到的数组键。
因此,要检查是否存在 Flash 消息,您将执行以下操作:
$session->check('Flash.flash')
或者,如果您在设置 flash 消息时指定了一个键,您将执行以下操作:
$session->check('Flash.INSERT_CUSTOM_KEY')
推荐阅读
- c++ - 我如何在其中应用 C++ 数组?
- windows - 使用 VBScript 运行 OSPP.vbs
- mongodb - 如何使用多个值更新数组中的多个项目
- reactjs - 标准 React Native 组件的包装器在 Web 浏览器中不起作用
- excel-formula - 根据给定日期的频率获取下一个到期日
- r - 在一行中进行字符串比较并删除包含相同的行
- javascript - 正则表达式:从camelCase中提取大写字母
- android - 如何在一个应用程序中制作不同的共享首选项文件
- javascript - 如何根据鼠标在 x=y 线上方/下方的位置使图像不显示?
- php - REACT + PHP - 仅在 POST 请求中阻止了我的 CORS 策略