0

I have an item in the navbar that links to a page view which can only be accessed by authenticated users.

I want the menu item visible for anonymous users, and also to have them redirected to login if they try to access it. This seems like a common use-case. I see a plethora of modules that accomplish this in Drupal 7, but I don't see any for Drupal 8.

How can I show the navbar for anonymous users that prompts users to login with Drupal 8?

1 Answer 1

2

As you know, Drupal excludes menu links that the user doesn't have permission to view.

One way around this is to build a menu specifically for anonymous users using the same titles as your other menu, but all pointing to the /user/login?destination=my/view/path path. Once the that menu is built, you can create a menu block from it that only displays for the anonymous user role.

After adjusting the original menu block such that it only displays for the authenticated user role, you will effectively have menu items that display for both roles and prompts a user to login when viewing anonymously. For good measure, you might want to set your Basic site settings such that 403 requests are redirected to /user/login in case the user navigates to the views page directly.

3
  • How do I tell the new menu to only appear for anon users? Also, I temporarily changed the href of my menu item from /my/view/path to /user/login?destination=my/view/path. Users still get in, anon members still see it, are there any disadvantages to just leaving it this way? Other than the URL not being as pretty as it could have been... May 26, 2016 at 13:53
  • 1
    On the block administration page there's a Roles section that lets you set the block's visibility for specified roles
    – Shawn Conn
    May 26, 2016 at 15:59
  • I got it working by following your instructions. Thanks a bunch May 26, 2016 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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