CakePHP 3.0 Flash Message

2020-08-04 04:24发布

In CakePHP 2.0, I can check if there a flash message by using

if($session->check('Message.flash')){...}

I understand that in CakePHP 3.0, I read the doc that I can check if there a flash message by using

Layout

echo $this->Flash->render('auth');

Template/Users/login

echo $this->Flash->render();
if($this->request->is('flash')){...}else{...}

But in my view is when I added the above condition is not showing anything. My controller code is below

$this->Flash->error('The email address and/or password you specified are not correct.');
return $this->redirect(array('controller'=>'users', 'action' => 'login'));

Can anyone point to me what else is missing? I want to check if a flash message is shown in CakePHP 3.0. Thanks.

3条回答
叛逆
2楼-- · 2020-08-04 04:45

In Controller action

$this->Flash->success(__('The data has been saved.'));

OR

$this->Flash->error(__('The data could not be saved. Please, try again.'));

Put anywhere in View or Layout file

<?php
$class = 'message';
if (!empty($params['class'])) {
    $class .= ' ' . $params['class'];
}
?>
<div class="<?= h($class) ?>"><?= h($message) ?></div>
查看更多
霸刀☆藐视天下
3楼-- · 2020-08-04 04:47

You can still do it in CakePHP 2 way that is read this value from session. You can access session in layout through request object.

$session = $this->request->session();
if ($session->check('Flash.flash')) {...}

Or if you want to check is there "auth" key message:

if ($session->read('Flash.flash.key' == 'auth')) {...}

This is how session array now looks with Flash, if you wanna do something else:

[
    ...
    'Flash' => [
        'flash' => [
            'message' => 'The page has been saved.',
            'key' => 'flash',
            'element' => 'Flash/success',
            'params' => []
        ]
    ]
    ...
]
查看更多
冷血范
4楼-- · 2020-08-04 04:50

Usually what I do, I create a custom flash message for all exceptions.

In Template/Elemen/Flash place custom_error.ctp

In your controller:

$this->Flash->customError('A message... ',['key' => 'cutom_error_key',]);

And in the view/template:

$this->Flash->render('custom_error_key');
查看更多
登录 后发表回答