Create a custom permission in Drupal 8 | Drupal 8

Create a custom permission in Drupal 8

Submitted by editor on Sat, 12/05/2015 - 17:53
Question

How to create a custom permission in Drupal 8 ?

Example with a module 'mymodule'

Step 1.
Create if not exist yet, mymodule.permissions.yml (root of mymodule)
Add your new permission like:

mymodule test_permission:
    title: 'My Test Permission'
    description: 'The description'
    restrict access: false

Step 2.
On your mymodule.routing.yml
mymodule.home:
  path: 'test/home'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Test::home'
    _title: 'My test Home'
  requirements:
    _permission: 'mymodule test_permission'

Set permissions on : /admin/people/permissions

 

Permissions AND condition

Must have all
Example:
  requirements:
    _permission: 'mymodule test_permission, mymodule permission'

Permissions ORcondition

Must have at least one
Example:
  requirements:
    _permission: 'mymodule test_permission+mymodule permission'

Comments

Tim Kariuki (not verified)

Wed, 11/01/2017 - 07:12

This is why I love Drupal. I thought it would take forever to achieve this but just as you have demonstrated, with a few lines of code, I have managed to restrict access to the correct user roles. Thanks a lot.

Add new comment

Plain text

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