【问题标题】:CakePHP 3.0 Flash MessageCakePHP 3.0 Flash 消息
【发布时间】:2015-09-06 22:06:57
【问题描述】:

在 CakePHP 2.0 中,我可以通过使用检查是否有 flash 消息

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

我了解在 CakePHP 3.0 中,我阅读了 doc,我可以使用它检查是否有 flash 消息

布局

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

模板/用户/登录

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

但在我看来,当我添加上述条件时,并没有显示任何内容。我的控制器代码如下

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

谁能指出我还缺少什么?我想检查一下在 CakePHP 3.0 中是否显示了 Flash 消息。谢谢。

【问题讨论】:

  • 我不确定我是否理解您为什么要检查是否有 Flash 消息?如果它在那里,为什么不直接使用代码来显示它?此外,is('flash') 将在控制器中使用,用于检测生成请求的用户代理是否是 Flash,而不是您使用它的目的。
  • 感谢您的回复。我想在登录页面中显示默认消息。如果有闪消息,我想用闪消息替换默认消息。因此,我想在视图中进行条件检查。不过我可以在 CakePHP 2.0 中实现。
  • 通常您会在 Controller 或其他地方检查条件,然后根据结果设置 flash 消息。然后,您只需在所需的位置显示 Flash 消息即可。最好将逻辑排除在您的视图及其所属位置之外。

标签: php cakephp cakephp-2.0 cakephp-3.0


【解决方案1】:

通常,我会为所有异常创建自定义 Flash 消息。

在 Template/Elemen/Flash 中放置 custom_error.ctp

在您的控制器中:

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

在视图/模板中:

$this->Flash->render('custom_error_key');

【讨论】:

    【解决方案2】:

    你仍然可以用 CakePHP 2 的方式从会话中读取这个值。您可以通过请求对象访问布局中的会话。

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

    或者如果你想检查是否有“auth”关键信息:

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

    如果您想做其他事情,这就是现在使用 Flash 时会话数组的外观:

    [
        ...
        'Flash' => [
            'flash' => [
                'message' => 'The page has been saved.',
                'key' => 'flash',
                'element' => 'Flash/success',
                'params' => []
            ]
        ]
        ...
    ]
    

    【讨论】:

      【解决方案3】:

      在控制器动作中

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

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

      放置在 View 或 Layout 文件中的任意位置

      <?php
      $class = 'message';
      if (!empty($params['class'])) {
          $class .= ' ' . $params['class'];
      }
      ?>
      <div class="<?= h($class) ?>"><?= h($message) ?></div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-29
        • 2016-04-09
        相关资源
        最近更新 更多