XF 2.1 Add secondary usergroup

Edman

Member
I'm looking to add a secondary usergroup to a xenforo user from my site's code.

I've figured out how to get user details and check if the user already has the usergroup

Code:
                $dir = "/path";
                require($dir . '/src/XF.php');
                XF::start($dir);

                $userid = 1;
                $site_usergroup = 14; // this usergroup is created in Xenforo

                $user = \XF::em()->find('XF:User', $userid);
                if ($user->isMemberOf($site_usergroup) == FALSE)
                {
                    # add usergroupid to user
                }
I see in XF there is a removeUserFromGroup($groupId) function

I was hoping there was a $user->addUserToGroup($groupId) function, but I can't find it :(

Thanks
 
There is a secondary_group_ids array field of User entity.

So in "# add usergroupid to user" you can simply add an id to that array and trigger User save:

PHP:
$user->secondary_group_ids[] = 14;
$user->save();
 
Use the service please.

PHP:
      /** @var \XF\Service\User\UserGroupChange $userGroupChange */
      $userGroupChange = \XF::service('XF:UserGroupChange');
      $userGroupChange->addUserGroupChange($user->user_id, '<a key describing the change>', [<array of user group ids to add to>]);
 
For those looking at this code in the future, just wanted to make a note that the line is
PHP:
      /** @var \XF\Service\User\UserGroupChange $userGroupChange */
      $userGroupChange = \XF::service('XF:User\UserGroupChange');
      $userGroupChange->addUserGroupChange($user->user_id, '<a key describing the change>', [<array of user group ids to add to>]);

And this code:
PHP:
$user->secondary_group_ids[] = 14;
$user->save();
doesn't work, as secondary_group_ids cannot be changed.
 
Back
Top Bottom