2013-07-30 45 views
2

我正在学习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; 
     } 

这是视图/ 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 .. 我希望我会得到你们一些帮助:)

+0

'$这个 - >形式 - > update'是不存在的功能。 – AD7six

回答

0

如果这是PostController,比你不要编辑调用$ this-> loadModel('Post');功能。

鉴于您需要一个隐藏字段,其ID为帖子。对编辑后

+0

我建议你,你去食谱博客教程。 – AtLeT

+0

如果我从控制器中删除$ this-> loadModel('Post')错误显示无法调用非成员findById(),因此我正在使用loadModel函数 – user2632669

+0

而且我尝试使用隐藏的id字段,但仍然它不工作:( – user2632669

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