问题
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.
回答1:
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');
回答2:
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' => []
]
]
...
]
回答3:
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>
来源:https://stackoverflow.com/questions/30963296/cakephp-3-0-flash-message