What does dynamic permission mean, in Drupal 8?
When should I use this?
2 Answers
In Drupal 8, the permissions a module defines are defined in a .permissions.yml file (such as the user.permissions.yml file used from the User module), which doesn't contain PHP code. As such, those are static permissions because they don't depend from any runtime condition, such as the node bundles defined from modules, the user roles present in the site, or the input filters implemented by modules.
Dynamic permissions are those permissions that depends from runtime conditions. For example, the Node module defines a set of permissions for each node bundle defined from modules. They cannot be statically set because the number and the type of node bundles can change from site to site.
In this case, Drupal allows to define in the .permissions.yml file a list of methods that return a list of extra permissions. This is what done, for example, in node.permissions.yml and filter.permissions.yml, where you find the following line.
permission_callbacks:
- Drupal\filter\FilterPermissions::permissions
If you look at the code for Drupal\filter\FilterPermissions::permissions()
, you will see how easy defining new dynamic permissions is: Return an array containing the title and description keys, keyed by the permission name.
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' => [
'#prefix' => '<em>',
'#markup' => $this->t('Warning: This permission may have security implications depending on how the text format is configured.'),
'#suffix' => '</em>'
],
];
}
}
I consider it generating permissions based on some data within your site.
For instance, I wanted to create permissions based on terms or vocabularies for roles, in regards to if they could use the functionality a contrib module I maintain provides:
http://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8
If you look at the NodePermissions class, it does something similar.