User Roles and Permissions

Public

http://www.dibe.gr/blog/drupal-7-create-users-and-roles-programmatically

</> CopyGet raw version
php
  1. //Create roles programmatically in Drupal 7
  2. $role = new stdClass();
  3. $role->name = 'editor';
  4. // $role->weight = 10;
  5. user_role_save($role);

Assign permissions to this role

</> CopyGet raw version
php
  1. // Role to grant the permissions to
  2. $editor_role = user_role_load_by_name('editor');
  3. $editor_rid = $editor_role->rid;
  4. // Define our 'editor' role permissions
  5. $editor_permissions = array(
  6. 'administer blocks' => TRUE, // Grant permission
  7. 'access dashboard' => FALSE, // Revoke permission
  8. ..., // more permissions' name
  9. );
  10. // Grant permissions to our 'editor' role
  11. user_role_change_permissions($editor_rid, $editor_permissions);

Create a user with this role

</> CopyGet raw version
php
  1. // Determine the roles of our new user
  2. $new_user_roles = array(
  3. DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  4. $editor_rid => TRUE,
  5. );
  6. // Create a new user
  7. $new_user = new stdClass();
  8. $new_user->name = 'john doe';
  9. $new_user->pass = 'mypassword'; // plain text, hashed later
  10. $new_user->mail = 'john@doe.com';
  11. $new_user->roles = $new_user_roles;
  12. $new_user->status = 1; // omit this line to block this user at creation
  13. $new_user->is_new = TRUE; // not necessary because we already omit $new_user->uid
  14. user_save($new_user);