Cakephp 3.x update a record without form

自闭症网瘾萝莉.ら 提交于 2019-12-13 07:58:41

问题


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.'));
        }
    }
}

回答1:


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

  • Creating Standalone Buttons and POST links


来源:https://stackoverflow.com/questions/35039232/cakephp-3-x-update-a-record-without-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!