XF 2.2 Adding/removing user groups in addon



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:
$userGroupChangeService = \XF::app()->service('XF:User\UserGroupChange');

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

$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 :)


XenForo developer
Staff member
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).