1

I know how to search for menu items created with *.links.menu.yml:

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_links = $menu_link_manager->loadLinksByRoute('user.page');
foreach ($menu_links as $menu_link) {
  // Do something
}

However I'm looking for a way to search for and update a menu item created with MenuLinkContent::create():

$home_new = MenuLinkContent::create(array(
  'title' => t('Home'),
  'link' => array('uri' => 'internal:/'),
  'menu_name' => 'main',
));
$home_new->save();

After creating this menu item, how do I look it back up again to modify it?

3

If you remember the id after saving the menu link

$id = $home_new->id();

You can load it directly:

$link = MenuLinkContent::load($id);

If you don't know the id, you can load the menu link by a property:

$links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['title' => 'Home']);

if ($link = reset($links)) {
  // found a link with title "Home"
}
2
  • Minor fix: if ($link = reset($links)) { – user20765 Jun 13 '19 at 8:54
  • To follow up on this, if you have the link path, you can get it with the link__uri property, e.g. $links = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(['link_uri' => 'internal:/contact-us']); – malcomio Jun 4 '20 at 20:02

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.