Созонов Алексей

Веб-разработчик

Добавить роль пользователю drupal

09.08.2015

Просто добавляем функцию в свой модуль и вызываем там, где она нам нужна

<?php

custom_add_role_to_user($user->uid, 'role name here');

/**
* Add a role to a user.
*
* @param $user
*   User object or user ID.
* @param $role_name
*   String value of role to be added.
*
* @see http_://drupal.org/node/28379#comment-4277052
* @see http_://api.drupal.org/api/drupal/modules--user--user.module/function/user_save
*/
function custom_add_role_to_user($user, $role_name) {
  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }
  // If the user doesn't already have the role, add the role to that user.
  $key = array_search($role_name, $user->roles);
  if ($key == FALSE) {
    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {
      $new_role[$rid] = $role_name;
      $all_roles = $user->roles + $new_role; // Add new role to existing roles.
      user_save($user, array('roles' => $all_roles));
    }
  }
}

/**
* Remove a role from a user.
*
* @param $user
*   User object or user ID.
* @param $role_name
*   String value of role to be removed.
*/
function custom_remove_role_from_user($user, $role_name) {
  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }
  // Only remove the role if the user already has it.
  $key = array_search($role_name, $user->roles);
  if ($key == TRUE) {
    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {
      // Make a copy of the roles array, without the deleted one.
      $new_roles = array();
      foreach($user->roles as $id => $name) {
        if ($id != $rid) {
          $new_roles[$id] = $name;
        }
      }
      user_save($user, array('roles' => $new_roles));
    }
  }
}
#Drupal