1

I would like to update role name programmatically in Drupal 7. Does Drupal provide its own functions to do that, or do we need to query the database and update the name manually?

Please note that this is not about changing the role a user has, but changing the name of a role.

2

Information about user roles should never be loaded/saved directly from the database, but using the functions the User module provides, such as:

As for changing the role name, that is not as simple as editing the role object and saving it, since the role name is required to be unique. (The name field, in the database, is the unique key for the role table.)

Before saving the role object, the code should verify the name is not already used, as the following code does.

// Load the role object from the database into the $role variable, using user_role_load()
// or user_role_load_by_name().
// The $role_name variable is assumed to contain the new name you want to give to the role.

if (!(bool) user_role_load_by_name($role_name)) {
  // There isn't a role with that name, so it's possible
  // to change the role object and save it.
  $role->name = $role_name;
  user_role_save($role);
}
else {
  // There is already a role using that name. 
  // Make the name unique, or abort the operation.
}

Using the functions made available from the User module is preferable, since it allows other modules to react to changes to roles. Those functions invoke at least one of the following hooks.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.