【问题标题】:CakePHP4 Edit doesnt update recordCakePHP 4 Edit 不更新记录
【发布时间】:2021-10-19 10:05:36
【问题描述】:

版本:4.2.9

我的编辑视图正在用数据填充我的输入,但是当我更改它们并单击保存时,它不会保存,而是给我“用户已保存”消息。

UsersController.php 编辑函数

    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => ['Userdata'],
        ]);
        if ($this->request->is(['post', 'put'])) {
          $user = $this->Users->get($id, [
              'contain' => ['Userdata'],
          ]);
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
    }

我的编辑.php

<div class="users form large-9 medium-8 columns content">
    <?php echo $this->Form->create($user) ?>
    <fieldset>
        <legend><?= __('Edit User') ?></legend>
        <?php
            echo $this->Form->control('userdata.Email');
            echo $this->Form->control('userdata.UserName');
            echo $this->Form->control('PasswordHashed', ['type' => 'password']);
        ?>
    </fieldset>
    <?= $this->Form->button(__('save')) ?>
    <?= $this->Form->end() ?>
</div>

【问题讨论】:

  • 通过设置调试消息,我看到它进入了被执行的 save() 函数,但在那之后似乎有些东西不起作用。
  • getting 用户记录(两次,没有充分的理由),但在保存之前没有更新它。看patchEntity

标签: php html model-view-controller cakephp


【解决方案1】:

你的更新代码不完整,你省略了patchEntity方法。

public function edit($id = null)
{
    // call query only once
    $user = $this->Users->get($id, [
        'contain' => ['Userdata'],
    ]);
    // Call the debug method just to test and understand your data
    // debug($user);
    // debug($this->getRequest()->getData()); // debug posted data
    if ($this->request->is(['post', 'put'])) {
      $user = $this->Users->patchEntity($user, $this->getRequest()->getData());
        // debug patched data debug($user); exit;
        if ($this->Users->save($user)) {
            $this->Flash->success(__('The user has been saved.'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
    $this->set(compact('user'));
}

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    相关资源
    最近更新 更多