在每个请求中插入Cakephp数据而不是更新

时间:2014-02-10 07:16:55

标签: php 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 view

<?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');  
?>

为什么代码无效:( 当我提交代码时,不是编辑而是保存新的

2 个答案:

答案 0 :(得分: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')); 
          }   
         }  
    }

答案 1 :(得分: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();
        }
 }

您的观点看起来不错

相关问题