Back to UserHelper class

Method setUserGroups

public static bool
setUserGroups
(mixed $userId, mixed $groups)
Method to set the groups for a user.
Parameters
  • int $userId The id of the user.
  • array $groups An array of group ids to put the user in.
Returns
  • bool True on success
Since
  • 1.7.0
Class: UserHelper
Project: Joomla

Method setUserGroups - Source code

/**
 * Method to set the groups for a user.
 *
 * @param   integer  $userId  The id of the user.
 * @param   array    $groups  An array of group ids to put the user in.
 *
 * @return  boolean  True on success
 *
 * @since   1.7.0
 */
public static function setUserGroups($userId, $groups)
{
    // Get the user object.
    $user = User::getInstance((int) $userId);
    // Set the group ids.
    $groups = ArrayHelper::toInteger($groups);
    $user->groups = $groups;
    // Get the titles for the user groups.
    $db = Factory::getDbo();
    $query = $db->getQuery(true)->select($db->quoteName(['id', 'title']))->from($db->quoteName('#__usergroups'))->whereIn($db->quoteName('id'), $user->groups);
    $db->setQuery($query);
    $results = $db->loadObjectList();
    // Set the titles for the user groups.
    for ($i = 0, $n = \count($results); $i < $n; $i++) {
        $user->groups[$results[$i]->id] = $results[$i]->id;
    }
    // Store the user object.
    $user->save();
    // Set the group data for any preloaded user objects.
    $temp = Factory::getUser((int) $userId);
    $temp->groups = $user->groups;
    if (Factory::getSession()->getId()) {
        // Set the group data for the user object in the session.
        $temp = Factory::getUser();
        if ($temp->id == $userId) {
            $temp->groups = $user->groups;
        }
    }
    return true;
}