Recently i had some task, in which i wanted to add the specific role during registration programatically.
After searching in Drupal API, i came across two function that can do the task for me.
function user_role_load_by_name($role_name) 
This function fetches the role from the role name, and it will return a fully-loaded role object if a role with the given name exists, or FALSE otherwise.
I used this function to load the role object which i passed as string in $role_name.
Now function  user_multiple_role_edit() will allow to add roles to the users.
function user_multiple_role_edit($accounts, $operation, $rid) {

Here is the snippet which i used for managing the roles.
function HOOKNAME_user_insert(&$edit, $account, $category){

    //Add the account executive role to the user.

    $role_name = 'teacher'; // The name of the role to add.

      if ($role = user_role_load_by_name($role_name)) {

        user_multiple_role_edit(array($account->uid), 'add_role', $role->rid);





Post new comment