Cakephp 3.x不使用表单更新记录
在我的Cakephp 3.x不使用表单更新记录,cakephp,cakephp-3.0,Cakephp,Cakephp 3.0,在我的users/index页面中,我通过执行以下操作基本上列出了users表中的每个用户: <?php foreach ($users as $user): ?> <tr> <td><?= h($user->name) ?></td> <td><?= h($user->email) ?></td> <td><
users/index
页面中,我通过执行以下操作基本上列出了users
表中的每个用户:
<?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; ?>
但是,它在表单之外不起作用,而且表显然不是表单
非常感谢您对如何解决问题的任何帮助或指导
编辑
根据要求,我提供了用于保存用户数据(如果从表单保存)的代码段:
一个非常简单的方法可以是下面描述的方法。它不使用Ajax,只使用一个简单的POST请求,这意味着当角色改变时页面会被重新加载 按如下方式修改您的视图:
<?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; ?>
注意:代码未经测试,并且缺少错误处理
看
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.'));
}
}
}
<?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; ?>
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());
}