Drupal – Add and Remove Role From User

The following codes helps you to add or remove role from user. Assume u have a role called contractor.

Add the contractor role for the logged in user

// Get logged in user
global $user;

// Find the id for role "contractor";
$role_id = db_result(db_query("SELECT rid FROM {role} WHERE name = 'contractor'"));

// Insert contractor role for the logged in user only if the current user doesn't have the contractor role
if (!db_result(db_query("SELECT 1 FROM {users_roles} WHERE uid = %d AND rid = %d", $user->uid, $role_id))) {
  db_query("INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)", $user->uid, $role_id);
}

 

Remove the contractor role for the logged in user

// Get logged in user
global $user;

// Find the id for role "contractor";
$role_id = db_result(db_query("SELECT rid FROM {role} WHERE name = 'contractor'"));

// Remove contractor role for the logged in user
db_query("DELETE FROM {users_roles} WHERE uid = %d AND rid = %d", $user->uid, $role_id);

 

Done =)

Reference: need to remove role on purchase

2 thoughts on “Drupal – Add and Remove Role From User”

Leave a reply to ykyuen Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.