我正在尝试检查用户试图删除的录音是否有任何附加记录(在这种情况下是附加费用声明的用户)。我可以使用beforeDelete()模型函数做到这一点。但是,如果找到记录并且不允许删除,我想传回一条flash消息,但我只是得到以下错误:
Fatal error: Call to a member function setFlash() on a non-object in...
继承我的代码:
public function beforeDelete($cascade = false) {
$count = $this->ExpenseClaim->find("count", array(
'conditions' => array('ExpenseClaim.user_id' => $this->id)
));
if ($count == 0) {
return true;
} else {
$this->Session->setFlash('User cannot be deleted as they have ' . $count . 'number of expenses claims already in the system');
return false;
}
}
有人能指出我正确的方向吗?
提前致谢
答案 0 :(得分:4)
您应该在控制器上检查用户是否无法删除,并从那里设置Flash消息。
当您在false
模型中返回User
时,如果无法删除用户,则很简单:
if(!$this->User->delete($id){
$this->Session->setFlash('User cannot be deleted');
}else{
//....
}
如果您想向用户提供更多详细信息,我建议您在User
模型中创建一个功能,以检查要删除的用户的声明数。
这样,您可以在控制器中执行以下操作:
if($count = $this->User->getClaims($id)){
$this->Session->setFlash('User cannot be deleted as they have ' . $count . 'number of expenses claims already in the system');
$this->redirect(array('controller' => 'User', 'action' => 'index'));
}
在User
模型中使用此功能:
public function getClaims($id){
return $this->ExpenseClaim->find("count", array(
'conditions' => array('ExpenseClaim.user_id' => $this->id)
));
}
虽然最好直接调用ExpenseClaim
模型。
答案 1 :(得分:2)
在Model
中设置来自beforeDelete()的flash消息public function beforeDelete($cascade = false) {
//count query
$count = $this->ExpenseClaim->find("count", array(
'conditions' => array('ExpenseClaim.user_id' => $this->id)
));
//count checking
if ($count == 0) {
return true;
} else {
//custom flash message
SessionComponent::setFlash('User cannot be deleted as they have ' . $count . 'number of expenses claims already in the system');
return false;
}
}
答案 2 :(得分:-1)
//e.g. in UserController.php, within public function delete($id){...}
if(!$this->User->delete($id)) {
if(!$this->Session->check('Message.flash')) {
$this->Session->setFlash(__('The User could not be deleted'));
}
} else {
//success stuff
}
这一点是允许在beforeDelete()中设置的flash消息如果存在则保持不变,但如果由于某些其他原因删除失败则提供不同的消息。