Drupal 8 - Programmatically hide or show menu items

Note Statistics

Note Statistics

  • Viewed 35 times
  • Bookmarked 1 times
  • 2 Grateful readers

When a user is not allowed to see a page, menu links leading to this page are also hidden from menus. However, there are times that this restriction mechanism is not enough, and you need to programmatically hide/show menu items.

A typical page is the registration page ( It actually redirects to the account edition for logged in user). Logged in users can still see the registration link on the account menu. Even though they might have access, it is pointless to show this link in a menu. How can we hide it?

A solution to hide a menu item is to use the hook_preprocess_menu. In the example below we hide the registration menu when a user is logged in.

function mymodule_preprocess_menu(&$variables) {
  // Hide registration link for the authenticated user.
  $items = $variables['items'];
  foreach ($items as $key => &$item) {
    // Hide  link if the user is logged in.
    if ($item['url']->getRouteName() == 'user.register' && \Drupal::currentUser()->isAuthenticated()) {
      unset($variables['items'][$key]);
    }
  }
}
Authored by
AbdulK
Tags