CakePHP - 编辑在尝试验证失败时丢失URL变量

时间:2011-04-07 14:25:27

标签: php cakephp cakephp-1.3

用户从这里开始:

/admin/cuisines/edit/16

用户输入的内容违反了验证规则并点击了提交。用户被带到这里:

/admin/cuisines/edit/16

用户认为它有效并再次点击提交 - 然后他们会被带到这里:

/admin/cuisines/edit/

用户更正了他们的错误,点击提交,而不是编辑,它将其保存为表格中的新项目,因为没有ID。

我的代码:

    function admin_edit($id = null) { // EDIT ***********

    if (!$id && empty($this->data)) {
        $this->Session->setFlash(__('Invalid cuisine', true));
        $this->redirect(array('action' => 'index'));
    }
    if (!empty($this->data)) {
        if ($this->Cuisine->save($this->data)) {
            $this->Session->setFlash(__('The edits to this cuisine have been saved', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The edits to this cuisine could not be saved. Please, try again.', true));
        }
    }
    if (empty($this->data)) {
        $this->data = $this->Cuisine->read(null, $id);
    }
}

对我做错了什么的想法?我以为我就像教程那样做了,但是 - 我不得不猜测Cake很聪明,不会让这种情况发生 - 即 - 我的假设是我做错了。

1 个答案:

答案 0 :(得分:3)

为避免在提交修改表单时保存新项目,请确保该ID的表单字段存在。

<?php echo $this->Form->input('id'); ?>

此字段将自动隐藏,因为它是模型主键。

同时检查HTML中的表单操作属性。我有时必须手动设置它以避免它出错。

<?php echo $this->Form->create('Cuisine', array(
  'url' => array(
    'action' => 'edit',
    $this->Form->value('id')
   )
)); ?>