2014-01-27 60 views
0

我目前有一個cakephP探針: 如果我打開/ users/edit/4例如,在用戶數據庫中創建一個新的空用戶條目。cakePHP用戶編輯創建空的用戶

我UsersController:

public function edit($id = null) { 
     if (!$this->User->exists($id)) { 
     throw new NotFoundException(__('Invalid user')); 
    } 
    if ($this->request->is(array('post', 'put'))) { 
     if ($this->User->save($this->request->data)) { 
      $this->Session->setFlash(__('The user has been saved.')); 
      return $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The user could not be saved. Please, try again.')); 
     } 
    } else { 
     $options = array('conditions' => array('User.' . $this->User->primaryKey => $id)); 
     $this->request->data = $this->User->find('first', $options); 
    } 
} 

我在做什麼錯?

隨着親切的問候,

Battlestr1k3

回答

0

您沒有添加$id

public function edit($id = null) { 
    if (!$this->User->exists($id)) { 
     throw new NotFoundException(__('Invalid user')); 
    } 

    if ($this->request->is(array('post', 'put'))) { 
     $this->request->data['User']['id'] = $id; 
     if ($this->User->save($this->request->data)) { 
      $this->Session->setFlash(__('The user has been saved.')); 
      return $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The user could not be saved. Please, try again.')); 
     } 
    } else { 
     $options = array('conditions' => array('User.' . $this->User->primaryKey => $id)); 
     $this->request->data = $this->User->find('first', $options); 
    } 
} 
+0

沒有必要assignto $用戶數據。您可以直接修改$ this-> request-> data。 – mark

+0

是的,你是對的。我只是這樣寫的,以便更容易看到。 – cornelb

+0

IMO單行'$ this-> request-> data ['User'] ['id'] = $ id'更容易閱讀:) – mark

0

試試這個

public function edit($id = null) { 
    if (!$this->User->exists($id)) { 
    throw new NotFoundException(__('Invalid user')); 
} 
if ($this->request->is(array('post', 'put'))) { 
     $this->User->id = $id; 
    if ($this->User->save($this->request->data)) { 
     $this->Session->setFlash(__('The user has been saved.')); 
     return $this->redirect(array('action' => 'index')); 
    } else { 
     $this->Session->setFlash(__('The user could not be saved. Please, try again.')); 
    } 
} else { 
    $options = array('conditions' => array('User.' . $this->User->primaryKey => $id)); 
    $this->request->data = $this->User->find('first', $options); 
} 

}

0

謝謝你們的快速答覆,他們都工作。 我很困惑,因爲當我用瀏覽器發出GET請求時,甚至調用了代碼,但問題是一個JavaScript函數,它在後臺發出了POST請求。

隨着親切的問候,

Battlestr1k3