在Model - CakePHP中设置来自beforeDelete()的flash消息

时间:2012-11-23 11:53:32

标签: cakephp

我正在尝试检查用户试图删除的录音是否有任何附加记录(在这种情况下是附加费用声明的用户)。我可以使用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;
    }

}

有人能指出我正确的方向吗?

提前致谢

3 个答案:

答案 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)

@motsmanish答案与最佳实践一致,因为它将代码放在防止它所属的位置删除 - 在Model中,而在CakePHP中,它属于beforeDelete()方法。为了扩充这一点,您可以在控制器中从您尝试删除的方法中引用会话Flash消息:

//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消息如果存在则保持不变,但如果由于某些其他原因删除失败则提供不同的消息。