在CakePHP中显示错误消息

用户名

我认为这是一件非常容易的事情。假设我认为控制器具有相应的功能。该函数如下所示:

class SomeController extends AppController{
public function action(){
.
.
.
if($this->request->is('post')){
   .
   .
   .
   if(some error appears)
      I want to get back to the "action" view with the data that was given to it before
   else
      continue processing
   .
   .
   .
}
populate $data and send it to the view "action";
}

我的意思是,我只想随时随地返回数据的特定视图。我用过redirect(array('controller'=>'some','action'=>'action')),但是没有用。而且使用render()不会占用$ data。请帮我。

Oldskool

您所描述的是所谓的Flash消息,可以在您的视图中显示它们,以告诉用户某些信息,例如保存操作失败或成功。您将需要在应用程序中加载Session组件和帮助程序才能使用它们。因此,在您的Controller(或AppController,如果您想在整个应用程序中使用它)中,添加:

public $components = array('Session');
public $helpers = array('Session');

然后在您的控制器中设置所需的Flash消息:

if (!$this->Model->save($this->request->data)) {
    // The save failed, inform the user, stay on this action (keeping the data)
    $this->Session->setFlash('The save operation failed!');
} else {
    // The save succeeded, redirect the user back to the index action
    $this->redirect(array('action' => 'index'));
}

确保通过简单地回显在您的视图中输出即显消息:

echo $this->Session->flash();

那应该做您想要的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章