2012-04-04 35 views
1

我並不是CakePHP的新手,雖然這是我在2.x中的第一個應用程序。我正在使用烘焙控制器&視圖,並且在編輯功能時遇到問題。編輯函數是INSERT而不是UPDATE CakePHP 2.1

對於初學者來說,這裏是進行烘烤:

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

當這個單獨

if (!$this->User->exists()) { 
      throw new NotFoundException(__('Invalid user')); 
     } 

離開我被告知,我有一個無效的用戶,甚至當我知道毫無疑問該用戶確實存在。

如果我把它改成這樣:

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

正確的編輯形式出現,並填充了正確的數據,但隨後在保存在試圖插入,而不是更新。

通常情況下,這是因爲CakePHP沒有可用的ID,但表單中有一個隱藏的ID字段,我甚至試圖在保存之前加入以下內容來強制解決該問題。

$this->request->data['User']['id'] = $id; 

任何想法這裏發生了什麼?

+1

「我甚至試圖強迫問題」 =如果你這樣做,你的代碼看起來100%foolprove>。對我來說,它應該更新正確...你調試$ ID? POST上的任何機會都是空的嗎?你需要在表單中隱藏「id」作爲隱藏輸入,以便發佈到正確的URL(帶有附加的ID) - 這可能是你的問題。 – mark 2012-04-04 12:10:21

+0

我認爲你是對的。我覺得沒有更多的調查是愚蠢的,但我試圖使用任何ID參數來編輯頁面,它仍然填充「正確」的形式(表中只有一個用戶,所以它填充與該用戶,無論我在URL中爲ID輸入的內容)。我得弄清楚這裏有什麼。 – Tspesh 2012-04-04 13:03:00

+0

在保存之前在線上調試()您的數據並將其發佈到您的問題中。 – Dave 2012-04-04 13:25:11

回答

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

介紹一下這裏的一些代碼? – Werner 2014-08-14 14:23:54

0

我得到了同樣的問題,通過烘烤,隱藏標識等生成的代碼.. 後來我發現,對數據庫ID字段沒有設置好的爲自動增量。

我只是設置爲自動增量和它的作品