【问题标题】:Edit function is INSERT instead of UPDATE CakePHP 2.1编辑功能是 INSERT 而不是 UPDATE CakePHP 2.1
【发布时间】:2012-04-04 11:25:15
【问题描述】:

虽然这是我在 2.x 中的第一个应用程序,但我对 CakePHP 并不完全陌生。我正在使用烘焙的控制器和视图,但编辑功能有问题。

对于初学者来说,这是烤出来的:

public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
        }
    }

当它被单独留下时

if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }

我被告知我有一个无效用户,即使我毫无疑问地知道该用户确实存在。

如果我把它改成这样:

 if (!$this->User->exists($id)) {
                    throw new NotFoundException(__('Invalid user'));
                }

出现了正确的编辑表单,并填充了正确的数据,但在保存后它会尝试插入而不是更新。

通常这是因为 CakePHP 没有可使用的 ID,但表单中有一个隐藏的 ID 字段,我什至试图通过在保存之前添加以下内容来强制解决此问题。

$this->request->data['User']['id'] = $id;

有什么想法吗?

【问题讨论】:

  • “我什至试图强迫这个问题” => 如果你这样做,你的代码看起来 100% 是傻瓜式的。对我来说它应该正确更新......你调试了 $id 吗?在 POST 上它是空的吗?您需要将“id”作为隐藏输入保留在表单中,以便发布到正确的 url(附有 id)——这可能是您的问题。
  • 我认为你是对的。我对没有进行更多调查感到愚蠢,但我尝试使用任何 ID 参数进入编辑页面,但它仍然“正确”填充表单(表中只有一个用户,所以不管怎样,它都会用那个用户填充它我在 URL 中为 ID 输入的内容)。我得弄清楚这里发生了什么。
  • debug() 你的数据在保存前就行了,并发布在你的问题中。

标签: cakephp insert edit cakephp-2.1


【解决方案1】:
public function edit($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            $user_data = $this->User->findById($id);
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'), 'flash');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'flash');
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
       }

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,烘焙生成的代码、隐藏的 id 等。 然后发现数据库上的字段id没有设置为自增。

    我刚刚设置为自动增量,它可以工作

    【讨论】:

      猜你喜欢
      • 2013-10-11
      • 2021-10-20
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多