Cakephp 3.x更新没有表单的记录 [英] Cakephp 3.x update a record without form
问题描述
在我的 users / index
页面上,我基本上通过执行以下操作列出 users
表中的每个用户:
In my users/index
page I basically list every user in the users
table by doing the following:
<?php foreach ($users as $user): ?>
<tr>
<td><?= h($user->name) ?></td>
<td><?= h($user->email) ?></td>
<td><?= h($user->phone_nr) ?></td>
<td><?= h($user->role)?></td>
</tr>
<?php endforeach; ?>
User.role
字段为枚举
类型,有两个选择:'user'
或'admin'
。
User.role
field is an enum
type with two choices: 'user'
or 'admin'
.
我不仅需要列出用户的角色,还需要有一个下拉菜单,以便能够立即对其进行更改。所以基本上我需要这样的东西:
Instead of just listing the user's role, I need to have a dropdown to be able to change it right away. So basically I need something like:
echo $this->Form->input('role', ['type' => 'select','label' => 'Role', 'options' => ['user' => 'user', 'admin' => 'admin']]);
但是,它不适用于表格之外,表显然不是表格。
However, it doesn't work outside of a form and the table is obviously not a form.
非常感谢您提供有关解决方法的帮助或指导。
Any help or guidance for how to solve is much appreciated.
编辑
根据要求,我提供用于保存用户数据(如果从表单保存)的代码段:
As requested, I provide the code snippet that is used to save user data (if saved from a form):
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
}
推荐答案
一种非常简单的方法可能是下面描述的方法。它不使用Ajax,仅使用一个简单的POST请求,这意味着在更改角色后将重新加载页面。
A very simple approach could be the one described below. It makes use of no Ajax, just a simple POST request, which means the page is reloaded when the role is changed.
按如下所示修改视图:
<?php foreach ($users as $user): ?>
<tr>
<td><?= h($user->name) ?></td>
<td><?= h($user->email) ?></td>
<td><?= h($user->phone_nr) ?></td>
<td><?= h($user->role)?></td>
<td>
<?= $this->Form->postButton('Toggle Role',
['controller'=>'users','action'=>'toggle_role',$user->id,$user->role])?>
</td>
</tr>
<?php endforeach; ?>
向您的控制器添加操作:
Add an action to your controller:
public function toggle_role($id,$existing_role){
$users = TableRegistry::get('Users');
$user = $users->get($id);
$user->role = ($existing_role == 'admin')?'user':'admin';
$users->save($user);
return $this->redirect($this->referer());
}
注意:该代码未经测试,并且缺少错误处理
请参见
- Creating Standalone Buttons and POST links
这篇关于Cakephp 3.x更新没有表单的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!