通常,处理错误的常用方法是简单地执行重定向,如下所示:
if ({something that is error}) {
$this->Session->setFlash(__('Error message'), true);
$this->redirect(array('controller' => 'some_controller', 'action' => 'some_action'));
}
但是,我在方法的if ($this->request->is('post')) {
部分进行了多次检查。如果任何检查失败,我想退出其余检查,将用户返回到具有之前输入的所有设置的表单,这样他们就不必再次填写表单。我该如何做到这一点?
public function custom_method() {
// get some information here
if ($this->request->is('post')) {
// do_check
if (!do_check) {
// set flash
// log error
// don't run the rest of the checks - go to end of the if ($this->request->is('post'))
}
// do other check
if (!do_other_check) {
// set flash
// log error
// don't run the rest of the checks - go to end of the if ($this->request->is('post'))
}
// do database update
}
// do other stuff here
// then it goes to render view
}
答案 0 :(得分:0)
在与我的一位好朋友交谈后,我找到了一个很好的解决方案(感谢@utoxin)!他提到模型验证,帮助我朝着正确的方向前进。
以下是我将如何实现这一目标:
public function prepare() {
// do some stuff here
if ($this->request->is('post')) {
$postValid = true;
if ($postValid and !some_check) {
$this->log('Log error here', 'error');
$this->Model->invalidate('form_field', 'No valid installation file was found for this version.');
$postValid = false;
}
if($postValid){
// no error, do redirect, continue successfully
}
}
// do other stuff here
// show form
}