Programmatically assign permissions to roles

Last updated on 15/11/2017

Example for Drupal 8

  use Drupal\user\Entity\Role;
  use Drupal\user\RoleInterface;
 
  $roles = Role::loadMultiple([
    RoleInterface::ANONYMOUS_ID,
    RoleInterface::AUTHENTICATED_ID
  ]);
 
  $contentTypeName = 'article';
 
  $issueAccessPermissions = [
    "view any $contentTypeName content",
    "view own $contentTypeName content"
  ];
 
  foreach ($issueAccessPermissions as $permission) {
    $roles[RoleInterface::AUTHENTICATED_ID]->grantPermission($permission);
    $roles[RoleInterface::ANONYMOUS_ID]->revokePermission($permission);
  }

 

Example for Drupal 7

    // Rebuild node types so that permissions are available.
    node_types_rebuild();
 
    $site_node_types = node_type_get_types();
    $node_types_perm = ['article', 'review'];
 
    // Construct the permissions.
    $permissions = [];
    foreach ($node_types_perm as $node_type_perm) {
      // Make sure the node type actually exists.
      if (empty($site_node_types[$node_type_perm])) {
        continue;
      }
 
      $permissions[] = "set $node_type_perm published on date";
    }
 
    // Grant access to specified roles.
    $roles = ['editor', 'administrator'];
 
    foreach ($roles as $role_name) {
      $role = user_role_load_by_name($role_name);
      if (isset($role->rid)) {
        user_role_grant_permissions($role->rid, $permissions);
      }
    }