Michiel
Michiel

Reputation: 8103

Custom user-roles and -permissions in installation script

Is it possible to write some code in your .install-file of your D7 website which allows you to generate user roles and permissions automatically? I always though so, but right now, I can't think of a way to do it.
Any advice?

Upvotes: 1

Views: 201

Answers (1)

Clive
Clive

Reputation: 36955

Absolutely:

function mymodule_install() {
  // Make the new role
  $role = new stdClass;
  $role->name = 'new role name';
  $role->weight = 3;
  user_role_save($role);

  // Permissions to assign to the role.
  // Note these are defined in hook_permission()
  $perms = array(
    'access administration pages',
    'view content',
    'any other permission you want'
  );

  // Grant the permissions. This function takes care of all necessary cache resets
  user_role_grant_permissions($role->rid, $perms);
}

Upvotes: 1

Related Questions