2014-01-20 31 views
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')); 

}}

回答

1
  1. 你在你的代碼中的錯字 - 改變你的===;那麼你的if語句不應該被評估爲真

    if ($user['User']['group_id'] == '1') 
    
  2. 會話或者是一個組件(控制器層的一部分)或輔助(View層的一部分)的所有的時間 - 它並不打算在模型中使用,一般也不應該在模型中使用。而redirect()只是一個控制器方法。只要讓beforeDelete返回false,然後在你的控制器中檢查是否刪除失敗(即返回false),如果是,則顯示錯誤的flash消息並重定向。

+0

我試過你的建議,但它只是刪除了用戶,並沒有重定向:我添加了我試過的主要問題的代碼。 '$ user ['User'] ['group_id']'是獲取被刪除用戶組ID的正確方法嗎? – schnauss

+1

你的'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

+0

謝謝,這正指向了我正確的方向。不僅我的語法錯誤(=將一個變量設置爲另一個,==比較兩個變量,===要求它們是相同的類型),'$ user ['User'] ['group_id']'似乎不是足以返回被刪除的用戶的group_id。 – schnauss

相關問題