I have this id via $link->getParent():


How do I get the node id of that menu link?


Something like:

if ('entity.node.canonical' == $link->getRouteName()) {
  $params = $link->getRouteParameters();
  $nid = $params['node'];

You can load the node from the (already depreciated) entityManager using the UUID:

$node = \Drupal::entityManager()->loadEntityByUuid('6cf83fce-228f-42da-bc39-bea06c767510');
  • why would I want to use a deprecated method? :) whats the not deprecated way? thanks!
    – Alex
    May 21 '16 at 10:04
  • it says Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "1365f9ba-2052-4773-827a-2475f1347aa0" entity type does not exist."
    – Alex
    May 22 '16 at 11:31
  • 1
    I would use the depreciated method mostly because the documentation and tutorials haven't yet been updated to make it clear how to use the replacement interface based solution. And because D8 will have a long shelf life so I would not be too worried about using a D8-only solution. If you need more help more code/context would be useful.
    – acrosman
    May 23 '16 at 13:02
  • the menu:uuid string actually loads the menu link, not the corresponding node
    – Alex
    May 23 '16 at 13:26
  • see my above comment please
    – Alex
    Jun 7 '16 at 13:47

See EntityRepository::loadEntityByUuid() for a non-deprecated way of loading by UUID.

  • that would load the menu item, not the node?
    – Alex
    Nov 29 '17 at 13:29

Elaborating on simesy's answer.

$menu_id = $link->getParent();
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_item = $menu_link_manager->createInstance($menu_id);
if ('entity.node.canonical' == $menu_item->getRouteName()) {
  $params = $menu_item->getRouteParameters();
  $nid = $params['node'];
  • How to get a node by menu link as $entity->id() with bundle 'menu_link_content' inside of the function mymodulename_entity_update() ? If I use your way, I receive the error Call to undefined method Drupal\menu_link_content\Entity\MenuLinkContent::getRouteParameters()...
    – stckvrw
    Aug 9 at 14:16

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.