2014-02-10 35 views
0

我的操作編輯CakePHP的數據被插入,而不是更新的每個請求

function edit($id = null) 
    { 
     if (empty($this->data)) { 
     $this->Post->id = $id; 
     $this->data = $this->Post->read(); 
     } 
     else { 
     if ($this->Post->save($this->data)) { 

      $this->Session->setFlash('Your post has been updated.'); 
      $this->redirect(array('action' => 'index')); 
      } 
     } 
    } 

php來查看

<?php 
echo $this->Form->create('Post', array('action' => 'edit')); 
echo $this->Form->input('title'); 
echo $this->Form->input('body', array('rows' => '3')); 
echo $this->Form->input('id', array('type'=>'hidden'));  
echo $this->Form->end('Save Post'); 
?> 

爲什麼不工作密碼:( 當我提交的代碼沒有編輯,但保存新

+0

你缺少'$這個 - >後>創建()'插入時。但除此之外,你不應該使用read(),而是使用find()。 – mark

回答

0

試試這個

function edit($id = null) 
    { 
     if (empty($this->data)) { 
     $this->Post->id = $id; 
     $this->data = $this->Post->read(); 
     } 
     else { 
     $this->Post->id = $id; 
     if ($this->Post->save($this->data)) { 

      $this->Session->setFlash('Your post has been updated.'); 
      $this->redirect(array('action' => 'index')); 
      } 
     } 
    } 
+0

tks我可以做到! – Kull

0

試試這個在您的控制器動作

public function edit($id = null) { 
    $this->Post->id = $id; 
    if(!$this->Post->exists()){ 
     //That post doesn't exists 
     throw new NotFoundException(__('Post not exist')); 
    } 
    if ($this->request->is('post') || $this->request->is('put')) { 
      if ($this->Post->save($this->request->data)) { 
       $this->Session->setFlash(__('The post has been updated'),'success_flash'); 
       $this->redirect(array('action' => 'index')); 
      } else { 
       $this->Session->setFlash(__('The post could not be saved. Please, try again.'),'error_flash'); 
      } 
     } else { 
      $this->Post->recursive = -1; 
      $this->request->data = $this->Post->read(); 
     } 
} 

你的觀點看起來不錯

相關問題