Drupal 8: Create Module Permissions

Looking for how to create new module permissions in Drupal 8? Look no further, $module.permissions.yml to the rescue!

In Drupal 8 permissions are now defined in $module.permissions.yml file instead of using hook_permission().

Drupal 8 Static Permissions

Create a new file in the root of your module folder and name it my_module.permissions.yml.

# In my_module.permissions.yml file.
access all views:
  title: 'My module settings'
  description: 'A custom permission for your module settings page.'
  restrict access: TRUE

Drupal 8 Dynamic Permissions

In Drupal 8, you can support dynamic permissions by referencing a function that will dynamically define those permissions. This callback defines the permissions for core’s filter module.

# In filter.permissions.yml
permission_callbacks:
  - Drupal\filter\FilterPermissions::permissions
<?php
// in FilterPermissions.php

class FilterPermissions {
  public function permissions() {
    $permissions = [];
    // Generate permissions for each text format. Warn the administrator that any
    // of them are potentially unsafe.
    /** @var \Drupal\filter\FilterFormatInterface[] $formats */
    $formats = $this->entityManager->getStorage('filter_format')->loadByProperties(['status' => TRUE]);
    uasort($formats, 'Drupal\Core\Config\Entity\ConfigEntityBase::sort');
    foreach ($formats as $format) {
      if ($permission = $format->getPermissionName()) {
        $permissions[$permission] = [
          'title' => $this->t('Use the <a href="@url">@label</a> text format', ['@url' => $format->url(), '@label' => $format->label()]),
          'description' => String::placeholder($this->t('Warning: This permission may have security implications depending on how the text format is configured.')),
        ];
      }
    }
    return $permissions;
  }
}
?>

For more information, see https://www.drupal.org/node/2311427.

Comments

  1. how about content type or nodes? single pages as well.

  2. Hi, so with Drupal 8 i can add custom permissions, such as : allow one role ‘superrole’ to access on a specific url ?

  3. I’m very used to hook_permission. This is very very handy.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

All comments are held for moderation and only published when on topic and not rude. You'll even get little stars if you do an extra good job.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.

icon-search icon-link