必须提交两次编辑页面才能保存更改

时间:2013-01-09 20:00:34

标签: php forms cakephp

我有一个编辑页面,用于编辑博客帖子。这是控制器动作......

public function edit($id = null) {
    $post = $this->Post->findById($id);

    if(!$post) {
        throw new NotFoundException('Post not found');
    }

    if($this->request->is('post')) {
        $this->Post->id = $id;
        if($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Post updated!');
            $this->redirect('/');
        } else {
            $this->Session->setFlash('Unable to update post!');
        }
    }

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

    $this->set('tags', $this->Post->Tag->find('list'));
    $this->set('pageTitle', 'Edit blog post');
}

编辑页面视图......

<h1>Edit blog post</h1>

<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.body'); ?>
<?php echo $this->Form->input('Tag.Tag', array('type' => 'text', 'label' => 'Tags (seperated by space)', 'value' => $tags)); ?>
<?php echo $this->Form->input('Post.slug'); ?>
<?php echo $this->Form->end('Save Changes'); ?>

出于某种原因,当我进行更改并单击“保存更改”时,页面只会刷新,虽然更新会在刷新后反映在表单中,但我必须再次单击“保存更改”才能将其保存到数据库和Cake将我重定向到/

可能导致什么?

1 个答案:

答案 0 :(得分:1)

由于表单中没有Post.id,CakePHP会发送PUT请求(而不是POST请求)以在您的数据库中创建(或“put”)新行第一次。这不会通过您的请求检查:

if($this->request->is('post'))

现在,此时您的逻辑将使用以下代码获取相应帖子的整行:

$this->request->data = $post;

这将包含给定帖子的ID,因为它在您的find()结果中,因此第二次提交时,它有一个ID,因此发送POST请求而不是{ {1}}请求。

假设您只想编辑现有帖子,请在表单中添加PUT字段(FormHelper automagic应该为其创建隐藏字段,但您始终可以明确告诉它,如下例所示):

id

这应该传递ID,从而触发echo $this->Form->input('Post.id', array('type' => 'hidden'); 请求而不是POST请求,并立即传递您的提交。

相关问题