4

If I use Drupal::menuTree() to load a menu it seems to always have inActiveTrail set to FALSE for all my items.

As an example consider the following code:

$menu_tree = Drupal::menuTree();
$parameters = new MenuTreeParameters();
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

That code returns the top level of the main menu with inActiveTrail = FALSE for all items regardless of what page I am on.

I believe MenuTreeParameters::setActiveTrail() is meant to help here but then I have to pass in an active trail.

How do I get the active menu trail for the current page load so I can then pass it in?

2 Answers 2

7

MenuLinkTreeInterface::getCurrentRouteMenuTreeParameters() is what you want. To use the example above:

$menu_tree = Drupal::menuTree();
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters('main');
$parameters->setTopLevelOnly();
$main_menu_top_level = $menu_tree->load('main', $parameters);

The resulting menu tree should have inActiveTrail flagged.

2
  • Thanks, that seems to be exactly what I was looking for, although in the example I would replace the new MenuTreeParameters() line with your new getCurrentRouteMenuTreeParameters() line instead of putting it below the setTopLevelOnly() call.
    – rooby
    Apr 14, 2016 at 7:14
  • Makes sense. That was a quick copy/paste job. Fixed.
    – Shawn Conn
    Apr 14, 2016 at 16:39
3

Use the active menu trail service, menu.active_trail, returns \Drupal\Core\Menu\MenuActiveTrailInterface. You can then use it to identify the active trail(s), and then retrieve it from the menu tree(s). Saves a foreach loop over the various menu items and testing for inActiveTrail.

$ids = $this->activeTrail->getActiveTrailIds('main'); $parameters = (new MenuTreeParameters())->setActiveTrail($ids); $tree = $this->linkTree->load('main', $parameters); $active = $tree[reset($ids)]; // There may be more than one...

Your Answer

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

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