dsc6517 2018-04-26 12:22
浏览 38
已采纳

如何检查CakePHP 3中是否存在Flash消息?

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?

  • 写回答

4条回答 默认 最新

  • duanlaiyin2356 2018-04-26 12:52
    关注

    You can use key while setting the Flash. see below

    $this->Flash->set('Welcome, to the real world.', ['key' => 'alert']);
    

    check by key in render before call

    <?php 
    if($this->Flash->render('alert')){
        echo $this->Flash->render('alert');
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)