1

I've a node, which is linked to a sub menu in the main navigation. I would like to get the url and title for the parent menu of the sub menu selected.

I've used it, but it is not working. I'm trying to use it in hook_node_view()

$node_id = $entity->id();
      $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
      $result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
      $build['result'] = $result;
      kint($result);

In twig, I'm calling it as

{{ content.result }}

But it is not working..

5

If you want to get the parent of the menu link use getParent():

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
if ($link = reset($links)) {
  if ($parent = $link->getParent()) {
    $parent = $menu_link_manager->createInstance($parent);
    $parent_title = $parent->getTitle();
    $parent_url = $parent->getUrlObject()->toString();
  }
}
1

Get parent menu of any type of page:

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$route_match = \Drupal::routeMatch();
$route_name = $route_match->getRouteName();
$route_parameters = $route_match->getRawParameters()->all();
$menu_links = $menu_link_manager->loadLinksByRoute($route_name, $route_parameters);

if (!empty($menu_links)) {
  $menu_link = reset($menu_links);
  if ($parent = $menu_link->getParent()) {
    $parent = $menu_link_manager->createInstance($parent);
    $parent_title = $parent->getTitle();
    $parent_url = $parent->getUrlObject()->toString();
  }
}

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.