Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

Cakephp 3.x update a record without form

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...