1 user.module user_role_save($role)

Save a user role to the database.


stdClass $role: A role object to modify or add.

Return value

int: Status constant indicating if role was created or updated. The constant SAVED_NEW or SAVED_UPDATED will be returned depending on the operation performed.


core/modules/user/user.module, line 2595
Enables the user registration and login system.


function user_role_save($role) {
  // Trim spaces from names.
  $role->name = trim($role->name);
  $role->label = trim($role->label);
  $role->description = isset($role->description) ? trim($role->description) : '';

  if (!isset($role->weight)) {
    // Set a role weight to make this new role last.
    $weight = 0;
    foreach (user_roles(FALSE, NULL, TRUE) as $existing_role) {
      $weight = max($existing_role->weight, $weight);
    $role->weight = $weight + 1;

  // Let modules modify the user role before it is saved to the database.
  module_invoke_all('user_role_presave', $role);

  $config = config('user.role.' . $role->name);
  $config->set('name', $role->name);
  $config->set('label', $role->label);
  $config->set('description', $role->description);
  $config->set('weight', $role->weight);
  if (isset($role->permissions)) {
    $config->set('permissions', $role->permissions);
  $is_new = $config->isNew();
  if ($is_new) {
    module_invoke_all('user_role_insert', $role);
    $status = SAVED_NEW;
  else {
    module_invoke_all('user_role_update', $role);
    $status = SAVED_UPDATED;

  // Clear the user access cache.

  return $status;