3

Maybe this is a noob question but here goes:

I have a menu a menu that contains four links. However, I need one of the items to be accessible only if the current user has "beneficiary" as role.

Since the user's 'roles' is an array containing all kind of roles, how can I set my route in a way that as long as the user has the correct role ?

IE, let's say that a random user has the following:

$user['roles'] = ['authenticated', 'beneficiary', 'elected'];

and would pass, but another random user having the following:

$user['roles'] = ['authenticated', 'elected'];

wouldn't.

I'm pretty sure there is a way but I can't find explicitely what I'm looking for in Drupal's documentation

Thank you in advance

  • So essentially you need to allow access to a route if the current user has the "beneficiary" role? – Clive May 3 '17 at 14:31
  • Is this Drupal 8? Are you defining your route in a custom entity routing.yml file? – user72086 May 3 '17 at 14:32
  • @Clive > yes, that's right, and yes this is Drupal 8 (I'll add a tag) – Jaeger May 3 '17 at 14:35
9

I've never personally tried this, but it looks like in your routing.yml file, you can specify a _role permission under requirements:

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

my_module.your_route:
  path: '/your_menu_path'
  defaults:
    _controller: '\path\to\your\controller'
    _title: 'Menu title'
  requirements:
    _role: 'beneficiary'
  • I just had issues wether to place it since there was several possibilities, but now it works fine, I get 404 with a wrong user, thank you ! – Jaeger May 3 '17 at 14:57
  • 1
    You can also specify multiple permissions by separating them with ',' (comma) for AND logic or '+' (plus) for OR logic (e.g., _role: 'administrator,beneficiary'). – pown Sep 21 '18 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.