Permissions

How to create a custom permission on Drupal 8 - 9

Tan Nguyen

|

You can define custom permissions on the permissions page, and check that permissions in your code to do different things based on the role of the user and the permissions.

Custom permission module example

I. Define custom permissions in a module.

1. lilengine_permission_example.info.yml

name: Permission Example
description: Provides examples for creating custom permissions.
core: 8.x
core_version_requirement: ^8 || ^9
type: module
package: Examples

2. lilengine_permission_example.permissions.yml

access secret notes:
  title: 'Access the secret notes'
  description: 'Access the secret notes when editing or creating nodes.'

Custom permissions

II. Check for that permission in your code.

lilengine_permission_example.module

<?php

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form.
 */
function lilengine_permission_example_form_node_form_alter(&$form, $form_state, $form_id) {
  // If the current user has the permission, show the secret notes.
  if (!\Drupal::currentUser()->hasPermission('access secret notes')) {
    return;
  }
  $form['secret_note_1'] = [
  	'#type' => 'item',
  	'#title' => t('Hello ! I am a secret note number 1'),
  	'#weight' => -100,
  ];
  $form['secret_note_2'] = [
  	'#type' => 'item',
  	'#title' => t('Hello ! I am a secret note number 2'),
  	'#weight' => -100,
  ];
}

check permission in code

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Comments

  • Allowed HTML tags: <em> <strong> <cite> <blockquote cite> <ul type> <ol start type> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [gist:#####] where ##### is your gist number to embed the gist
    You may also include a specific file within a multi-file gist with [gist:####:my_file].

Spread the word