编辑帖子在cakephp中不起作用

时间:2013-07-30 05:11:03

标签: cakephp

我正在学习Cakephp框架。我在尝试更新数据库记录时遇到问题。

这是编辑帖子的控制器代码....

$this->loadModel('Post');
            if($this->request->is('put')):
            $this->Post->id = $this->params['id'];
            if($this->Post->save($this->request->data)):
                $this->Session->setFlash(__('Page has been edited'));
                    $this->redirect('/User/index');
                endif;
            else:
            $this->set('postinfo', $this->Post->findById($this->params['id']));
            endif;
        }

这是view / edit.ctp文件

echo $this->Form->update('Post', array(
    'method' => 'put'
    ));
    echo $this->Form->input('title',array('type' => 'text','value'=>$postinfo['Post']['title']));
    echo $this->Form->input('body', array('type' => 'textarea','value' => $postinfo['Post']['body']));
    echo $this->Form->submit('Submit', array('class'=>'btn btn-primary'));
    echo $this->Form->end();

但是这段代码不会更新数据库中的记录......我尝试了book.cakephp.org教程和其他与cakephp相关的教程。 我希望我能从你们那里得到一些帮助:)

2 个答案:

答案 0 :(得分:0)

如果这是PostController,那么你不需要调用$ this-> loadModel('Post');功能

在视图中,您需要一个id为post的隐藏字段。

答案 1 :(得分:0)

编辑帖子的控制器代码

public function edit($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

   $post = $this->Post->findById($id);
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }

    if ($this->request->is('post') || $this->request->is('put')) {
         $this->Post->id = $id;

        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been updated.');
            $this->redirect(array('action' => 'index'));
        } 
    else {
            $this->Session->setFlash('Unable to update your post.');
        }
    }

    if (!$this->request->data) {
        $this->request->data = $post;
    }
}


view/edit.ctp file 

<h1>Edit Post</h1>
  <?php
    echo $this->Form->create('Post');
    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');
?>