More fun converting a Cake 2.x app to Cake 4.x. I have a ‘Manage Roles’ option in my user management setup. When I click ‘Manage Roles’ for a user, I’m taken to admin_groups.php
and I get an array of checkboxes read from my Groups
table. This is the code from my UsersController that brings these in:
$this->set('groups', $this->Groups->find('list', [
'keyfield' => 'id', 'valueField' => 'group_name',
'order' => ['group_name ASC']
])
);
I also contained my UserGroups
table when looking up the user, thinking that would help.
$user = $this->Users->get($id, [
'contain' => ['UserGroups'],
]);
Users, Groups, and UserGroups tables have the following associations:
Users hasMany UserGroups FK = user_id
UserGroups belongsTo Users FK = user_id
UserGroups belongsTo Groups FK = group_id
Groups hasMany Users FK = group_id
And here is the code from my admin_groups.php that displays the checkboxes and their labels.
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Edit User Roles for ' . $user->full_name) ?></legend>
<?php
echo $this->Form->control("UserGroups.group_id", [
'type' => 'select',
'multiple' => 'checkbox',
'options' => $groups,
'label' => '',
]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
I have no trouble displaying the checkboxes or selecting them and saving the result to the UserGroups
table; however, I’m struggling with displaying the checkboxes as “checked” after they’ve been selected. The user’s group memberships are retrieved by calling getGroups
in my UsersTable
:
public function getGroups($user_id, $keys = true)
{
// Get the user's group memberships
$groups = [];
foreach($this->UserGroups->find('all', ['contain' => ['Groups']])->where (['user_id' => $user_id]) as $data) {
$groups[$data->group->id] = $data->group->group_key;
}
return ($keys) ? $groups : array_keys($groups);
}
In the old days, all it took was a modification to the request object to populate the checkboxes, like so:
$this->request->data['UserGroup']['group_id'] = $this->User->getGroups($id, false);
Obviously, that’s forbidden now, so I’m looking for the Cake 4 equivalent.