Cakephp 3.x update a record without form -
in users/index
page list every user in users
table doing following:
<?php foreach ($users $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
field enum
type 2 choices: 'user'
or 'admin'
.
instead of listing user's role, need have dropdown able change right away. need like:
echo $this->form->input('role', ['type' => 'select','label' => 'role', 'options' => ['user' => 'user', 'admin' => 'admin']]);
however, doesn't work outside of form , table not form.
any or guidance how solve appreciated.
edit
as requested, provide code snippet used save user data (if saved 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 not saved. please, try again.')); } } }
a simple approach 1 described below. makes use of no ajax, simple post request, means page reloaded when role changed.
modify view follows:
<?php foreach ($users $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 action 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()); }
note: code not tested, , lacks error handling
see
Comments
Post a Comment