Cakephp 3.6.14:控制器获取 post 请求,重新打开视图并复制表单元素

Cakephp 3.6.14: Controller get post request, reopen view and copy form elements

我希望当用户提交表单时,此表单的内容将保存在数据库中,但随后它将重定向到具有与前一个字段相同的字段的相同表单,以便用户可以编辑其中的一些并再次保存。我怎样才能做到这一点?

代码

add.ctp:

<div class="roles form large-9 medium-8 columns content">
<?= $this->Form->create($role) ?>
<fieldset>
    <legend><?= __('Add Role') ?></legend>
    <?php
        echo $this->Form->control('name');
        echo $this->Form->control('description');
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

RolesController.php(添加功能)

public function add()
{
    $role = $this->Roles->newEntity();
    if ($this->request->is('post')) {
        $role = $this->Roles->patchEntity($role, $this->request->getData());
        if ($this->Roles->save($role)) {
            $this->Flash->success(__('The role has been saved.'));

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

要保持​​在同一页面/表单上,只需删除 return $this->redirect(['action' => 'index']) - 但我认为这不是您真正想要的。用户将在 "add" 页面上陷入困境 - 只需添加更多实体...

查看 CakePHP Controller tutorial - 它展示了如何创建 edit 方法和模板。这样做之后,您必须将重定向更改为 return $this->redirect(['action' => 'edit', $role->get('name')]) 之类的内容(假设 name 属性 适合识别角色实体)。