0
我試圖通過檢查group_id來防止管理員在CakePHP 2.4中意外刪除對方。我試過使用下面的刪除方法,但它仍然會刪除用戶,並且不會重定向。如何返回用戶的group_id,然後重定向並顯示一條說明「管理員無法刪除」的適當的閃光?CakePHP:在刪除之前檢查用戶的group_id
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(__('Invalid user'));
}
if ($user['User']['group_id'] == 1) { //Check user group
$this->Session->setFlash(__('Administrators can not be deleted'), 'flash/error');
$this->redirect(array('action' => 'index'));
}
if (!$this->User->delete()) {
$this->Session->setFlash(__('User could not be deleted'), 'flash/error');
$this->redirect(array('action' => 'index'));
}
if ($this->User->delete()) {
$this->Session->setFlash(__('User deleted'), 'flash/success');
$this->redirect(array('action' => 'index'));
}}
我試過你的建議,但它只是刪除了用戶,並沒有重定向:我添加了我試過的主要問題的代碼。 '$ user ['User'] ['group_id']'是獲取被刪除用戶組ID的正確方法嗎? – schnauss
你的'group_id'應該是數字,你爲什麼要用文字(''1'')來檢查它?你應該檢查'if($ user ['User'] ['group_id'] == 1)',儘管這不應該是它失敗的原因,因爲使用'=='PHP會相應地強制轉換以檢查值。在你的控制器中你調用'$ this-> User-> delete()',其中提供的['delete(id)'參數](http://book.cakephp.org/2.0/en/models/刪除-data.html#刪除)? – user221931
謝謝,這正指向了我正確的方向。不僅我的語法錯誤(=將一個變量設置爲另一個,==比較兩個變量,===要求它們是相同的類型),'$ user ['User'] ['group_id']'似乎不是足以返回被刪除的用戶的group_id。 – schnauss