Drupal 8: Create Module Permissions

Written by
Published
Updated
Typical Read
1 minutes

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.
[php]# 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[/php]

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.

[php]# In filter.permissions.yml
permission_callbacks:
– Drupal\filter\FilterPermissions::permissions[/php]

[php]<?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;
}
}
?>[/php]

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

4 comments on “Drupal 8: Create Module Permissions”.

Scott

# May 16, 2020

Great. Thanks.

# Nov 20, 2018

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

william

# Mar 15, 2017

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

# Apr 3, 2016

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

Join the conversation.

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

All comments posted on 'Drupal 8: Create Module Permissions' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

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.