[Solved] [Drupal] How to create user roles programmatically?

| | 1 min read

In Drupal there are by default two roles, Administrator and Authenticated user. If the requirement comes of creating additional roles then we can create and add as many roles in the default list of roles of Drupal as per our requirement.

In this article we will focus on how to create roles programmatically in Drupal.

In the modulename.install folder of your module folder, there is an install function. Inside this function we will write the code for creating the roles.

   * Implements hook_install().
  function photoshare_install() {
    $roles = user_roles(TRUE);
    $photographer_id = '';
    $premium_id = '';
    if (!in_array('photographer', $roles)) {
    $role1 = new stdClass();
    $role1->name = 'photographer';
    $photographer_role = user_role_load_by_name('photographer');
    $photographer_id = $photographer_role->rid;

To retrieve an array of roles matching specified conditions, we can use user_roles function. Then we can check whether the user role which we want to create is already in roles array. If the required role is not in the array then we can create a user role using object method and save it. Then we can fetch a user role by role name and then we can assign the role id to a variable.