1

ユーザーが削除しようとしているレコードに添付レコードがあるかどうかを確認しようとしています(この場合、添付費用請求のあるユーザー)。beforeDelete()モデル関数を使用してそれをうまく行うことができます。ただし、レコードが見つかり、削除が許可されていない場合は、フラッシュメッセージを返したいのですが、次のエラーが発生します。

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;
    }

}

誰かが私を正しい方向に向けることができますか?

前もって感謝します

4

3 に答える 3

4

コントローラでユーザーを削除できなかったことを確認し、そこからフラッシュメッセージを設定してください。

ユーザーを削除できない場合はモデル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モデルを直接呼び出す方が良いでしょうが。

于 2012-11-23T12:36:38.083 に答える
3

モデルのbeforeDelete()からのフラッシュメッセージを設定します

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;
}

}
于 2013-07-25T08:38:30.987 に答える
-1

@motsmanishの回答は、モデル内の削除を防ぐためのコードを配置するため、ベストプラクティスと一致します。また、CakePHPでは、これはbeforeDelete()メソッドに属します。これを補強するために、削除を試みているコントローラーのメソッドでセッションフラッシュメッセージを参照できます。

//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()で設定されたフラッシュメッセージが存在する場合はそれを保持できるようにすることですが、他の理由で削除が失敗した場合は別のメッセージを提供することです。

于 2014-08-26T13:46:02.687 に答える