Static and dynamic permissions in Drupal 8
Option 1 - Adding static permissions
Adding custom permissions is as simple as it can be, just create a MODULENAME.permissions.yml file and add the permission.
my custom permission:
title: 'My custom permission'
description: 'Just for testing purposes'
restrict access: true
When restrict access is set to true, the “Warning: Give to trusted roles only; this permission has security implications.” Message is shown in the description of the permission.
Use case
Some views can only be accessed for roles with the 'access private views' permission enabled.
In this use case, the module is called Dribbit, so we have a dribbit directory in modules/custom where all code is placed.
The dribbit.info.yml file
name: 'Dribbit demo module'
description: 'Demo module used on dribbit.eu'
type: module
core: 8.x
dependencies:
- views
package: 'Dribbit'
As you can see there is a dependency set on the views module. This is not necessary as we don't depend on views code. However, for me it is good practice to add the dependency as the permission we'll create is used solely for views. The fact that the permission is used solely for views is discussable keep in mind that this is just a use case example.
The dribbit.permissions.yml file
access private views:
title: 'Access private views'
description: 'Custom permission to handle access on private views pages.'
restrict access: false
Enable the module to see the new permission on /admin/people/permissions:

Now we can use the permission to restrict access inside a view:

Option 2 - Adding dynamic permissions
Add permission_callbacks to the MODULENAME.permissions.yml file.
permission_callbacks:
- \Drupal\MODULENAME\PERMISSIONSCLASS::METHOD
And create a src/PERMISSIONSCLASS.php file inside the module with a method to dynamically build permissions.
namespace Drupal\MODULENAME;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\node\Entity\NodeType;
/**
* Created by Dribbit.eu.
*/
class PERMISSIONSCLASS {
use StringTranslationTrait;
public function METHOD() {
$permissions = [];
foreach (NodeType::loadMultiple() as $type) {
$type_id = $type->id();
$type_params = array('%type_name' => $type->label());
$permissions['view ' . $type_id . ' content'] = [
'title' => $this->t('%type_name: View content', $type_params),
];
}
return $permissions;
}
}
The StringTranslationTrait is used to handle Drupal translations in a custom class.