Bobcares

Drupal 8 Assign Role to User Programmatically

by | Feb 7, 2024

Learn how to assign a role to a user programmatically in Drupal 8. Our Drupal Support team is here to help you with your questions and concerns.

Drupal 8 Assign Role to User Programmatically

Drupal is a powerful content management system with extensive customization options. One key aspect of Drupal’s functionality is its user access system based on roles. In certain cases, assigning roles based on specific business requirements becomes important.

Drupal 8 Assign Role to User Programmatically

Today, we are going to take a look at loading users, adding and removing roles, and managing roles efficiently in different scenarios in a Drupal environment.

Before delving into role management, we need to understand how to load users in Drupal. Here are some examples of how to load a specific user or the current user:

// Load a specific user (replace 2 with the desired user ID).
User::load(2);
// Load the current user.
User::load(\Drupal::currentUser()->id());

After loading a user, we can add or remove roles on specific requirements as seen below:

  • Adding a Role:

    Load a user (replace 2 with the desired user ID).
    $user = User::load(2);
    // Add the 'administrator' role.
    $user->addRole('administrator');
    $user->save();

  • Removing a Role:

    // Load a user (replace 2 with the desired user ID).
    $user = User::load(2);
    // Remove the 'administrator' role.
    $user->removeRole('administrator');
    $user->save();

Furthermore, we can assign a single role to a single user as seen below:

$uid = 3;
$role = user_role_load_by_name("editor");
user_multiple_role_edit(array($uid), 'add_role', $role->rid);

Alternatively, we can add the new role to existing roles for the user and then save the user object as seen below


$uid = 3;
$user = user_load($id);
$role = user_role_load_by_name("editor");
$user->roles = $user->roles + array($role->rid => $role->name);
user_save($user);

Here, we are assigning the ‘editor’ role to a user with a user id of 3.

If we want to assign a single role to multiple users as seen here:

$users = array(2, 5, 54);
$role = user_role_load_by_name("editor");
foreach($users as $uid) {
user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}

Here, we are assigning the ‘editor’ role to users with IDs 2, 5, and 54.

For more complex scenarios where multiple roles need to be assigned to multiple users, here is an example:


$users = array(2, 5, 54);
$roles = array("editor", "administrator");
foreach($users as $uid) {
foreach($roles as $role) {
$role = user_role_load_by_name($role);
user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}
}

By understanding the process of loading users and manipulating roles, developers can streamline the user access system to meet specific business requirements. These code snippets help Drupal developers looking to optimize their role management practices within the CMS.

[Need assistance with a different issue? Our team is available 24/7.]

Conclusion

In brief, our Support Experts demonstrated how to assign roles to user programmatically in Drupal 8.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF