XF 2.2 Adding/removing user groups in addon

sccrgy789

Member
Hi-

I'm wondering if someone can provide some definitive information on how to properly add/remove secondary user groups to/from a user in an addon. So far, I've consulted these threads:

My understanding is that you should use the user group change service like this:
PHP:
$userGroupChangeService = \XF::app()->service('XF:User\UserGroupChange');

// TO ADD
$userGroupChangeService->addUserGroupChange($user_id, 'some_key', $group_id);

// TO REMOVE
$userGroupChangeService->removeUserGroupChange($user_id, 'some_key');

As pointed out in another thread, this methodology doesn't work if you don't know the change set key for when the group was added. I basically need to be able to arbitrarily add a group to a user and later remove it (without knowing anything about how/when it may have been added). If the group is added via ACP, I still need to be able to remove it. I would have done this by directly modifying secondary_group_ids but another thread said that's not advisable and won't always work...

Any suggestions would be much appreciated. Thanks :)
 
The user group change service is there for situations where you're programmatically making group changes based on conditions/status. This allows it to handle scenarios where 2 situations might add the same user group; loss of one of those situations won't remove the user group, whereas manually changing the groups would remove the group, even though the group still should've been applied. If this is the case for what you're doing, you should be able to come up with some sort of unique identifier that represents the situation. As an example, purchasing a user upgrade uses userUpgrade-### as the change key.

If this doesn't describe your situation, that would imply that the change is essentially equivalent to an admin editing a user via the control panel. In which case, using a user entity and changing the secondary groups on that is basically the only way to do it. There isn't any reason that shouldn't work (it will handle permissions, etc).
 
Hi Mike!

Thanks for your response, you were exactly right about what I was trying to do. I got everything working and just wanted to post this sample code for others who may be trying to do the same thing:

PHP:
// Note: $user is assumed to be an \XF\Entity\User
// Add a secondary group to a user
$newSecondaryGroups = $user->secondary_group_ids;
array_push($newSecondaryGroups, $GROUP_ID_TO_ADD);
$user->set('secondary_group_ids', $newSecondaryGroups);
$user->save();


// Remove a secondary group from a user
$newSecondaryGroups = $user->secondary_group_ids;
foreach($newSecondaryGroups as $k => $v)
{
    if($v == $GROUP_ID_TO_REMOVE)
        unset($newSecondaryGroups[$k]);
}
$user->set('secondary_group_ids', $newSecondaryGroups);
$user->save();
 
Thanks for sharing. Exactly what I was looking for.
I was using the group change service, but your solution works better.
 
Back
Top Bottom