n How to add custom permissions in Drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Looking for how to create new module permissions in Drupal 8 ? In Drupal 8 permissions are now defined in MODULENAME.permissions.yml file instead of using hook_permission().

There are two types of permissions we can declare:

  1. Static, which are permissions that don't depend on any information in the system.
  2. Dynamic, which are permissions generated on the fly and are system-specific (e.g. permissions for each node type, user role, etc.).

Drupal 8 Static Permissions:

To declare static permisisons, you need to create a file in the root directory of your custom module and name it MODULENAME.permissions.yml.

Here's a sample syntax:

static permission 1:
  title: 'First level permission'
  description: 'Gives static permission 1 to the users.'

static permission 2:
  title: 'Second level permission'
  description: 'Gives static permission 2 to the users.'
  restrict access: true

Option restrict access will show an extra message in backend, warning administrators that this role has security implications and that granting it should be done with care.

Return back to your Back Office at "/admin/people/permissions" and you will see the new permissions .

Creating static permissions programmatically

 

Drupal 8 Dynamic Permissions:

In Drupal 8, you can support dynamic permissions by referencing a function that will dynamically define those permissions. 

To define a callback that will dynamically generate permissions, all you have to do is to create a new root level key named permission_callbacks and list those callbacks.

Here's an example:

permission_callbacks:
  - \Drupal\mymodule\DynamicPermissions::permissions

Naming does not have to follow a convention, though permissions() is pretty self-explanatory.

Each of callbacks listed here should return an array list of values with the same keys we used in the MODULENAME.permissions.yml file. This is the code you should have in MODULENAME/src/DynamicPermissions.php:


<?php

namespace Drupal\mymodule;

use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Class DynamicPermissions
 * @package Drupal\mymodule
 */
class DynamicPermissions
{

  use StringTranslationTrait;

  /**
   * @return array
   */
  public function permissions()
  {
    $permissions = [];

    $count = 1;
    while ($count <= 5) {
      $permissions += [
        "mymodule permission $count" => [
          'title' => $this->t('mymodule permission @number', ['@number' => $count]),
          'description' => $this->t('This is a sample permission generated dynamically.'),
          'restrict access' => $count == 2 ? true : false,
        ],
      ];
      $count++;
    }
    return $permissions;
  }
  
}

To see the new permissions just go back to Back Office at "/admin/people/permissions".

Drupal 8 Dynamic Permissions

 

Using custom permissions

There are 2 methods to use your custom permissions:

  • Directly in your code.
  • As access checks for certain routes.

Using custom permissions in the code:

if (\Drupal::currentUser()->hasPermission('mymodule permission 2')) {

  // The "mymodule permission 2" has been granted to the current user.

}else{

  // The "mymodule permission 2" has NOT been granted to the current user.

}

 

Route access checks:

Under route requirements you have to set the _permission to your custom permission.

mymodule_permissions.index:
  path: '/mymodule-permissions'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::index'
    _title: 'My Module Page Title'
  requirements:
    _permission: 'sample permission 2'

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook