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


Edit page has to be submitted twice for changes to be saved

我设置了一个编辑页面来编辑博客文章。这是控制器的动作…

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重定向到/

是什么导致的呢?

因为表单中没有Post.id, CakePHP第一次发送PUT请求(而不是POST请求)来创建(或"put")一个新行到数据库中。这没有通过您的请求检查:

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

现在,您的逻辑获得了对应帖子的整行,代码如下:

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

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

假设你只想编辑现有的帖子,添加一个id字段到你的表单(FormHelper自动应该使它隐藏字段,但你总是可以显式地告诉它,像下面的例子):

echo $this->Form->input('Post.id', array('type' => 'hidden');

这应该传递id,从而触发POST请求而不是PUT请求,并使您的提交立即通过。