Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 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.

EDIT

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.'));
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
309 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

Modify your view as follows:

<?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());
}

Note: The code is not tested, and lacks error handling

See


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...