3

I'm trying to get the parent menu item of node I am currently on:

$node_id = // some id
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
$parent = $menu_link->getParent();

but for some reason it always fails with this error:

Error: Call to a member function getParent() on array

When I inspect $menu_link I can clearly see it is there:

enter image description here

Also the method of getParent() seems to be correct: Docs

Would appreciate any help!

1
3

I think you need to reset the collection first, as the ::loadLinksByRoute() annotation states that it returns an array of MenuLinkInterfaces[].

See /core/lib/Drupal/Core/Menu/MenuLinkManagerInterface.php:


  /**
   * Loads multiple plugin instances based on route.
   *
   * @param string $route_name
   *   The route name.
   * @param array $route_parameters
   *   (optional) The route parameters. Defaults to an empty array.
   * @param string $menu_name
   *   (optional) Restricts the found links to just those in the named menu.
   *
   * @return \Drupal\Core\Menu\MenuLinkInterface[]
   *   An array of instances keyed by plugin ID.
   */
  public function loadLinksByRoute($route_name, array $route_parameters = [], $menu_name = NULL);

So do something like:

/** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node_id));
// Reset collection by retrieving the first item.
$menu_link = reset($menu_links);
// Now call the parent method.
$parent = $menu_link->getParent();
4
  • thanks for your answer, appreciate it. Now I'm getting a new error: Error: Call to a member function getParent() on bool. Do you have a second idea? – supersize Nov 17 '20 at 14:56
  • 1
    Seems like it has to do with that reset() returns false if the array is empty. – supersize Nov 17 '20 at 15:01
  • I think you are right about that. I guess you first need to double check that it is indeed returning an array of objects and not an empty array. – baikho Nov 17 '20 at 15:03
  • 1
    got it working, thanks for the answer, the reset() helped. – supersize Nov 17 '20 at 15:33

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.