2

我正在学习 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 相关的教程。我希望能得到你们的帮助:)

4

2 回答 2

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');
?>
于 2013-08-06T11:58:21.163 回答
0

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

在视图中,您需要一个带有帖子 ID 的隐藏字段。

于 2013-07-30T06:05:48.607 回答