How to update a menu link created with MenuLinkContent::create()?

by Wim Mostrey   Last Updated June 13, 2019 09:07 AM

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?

Tags : 8 navigation


Answers 1


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"
}
4k4
4k4
January 15, 2017 11:30 AM

Related Questions


Updated June 11, 2015 03:03 AM

Updated April 06, 2016 08:03 AM

Updated February 05, 2017 14:03 PM

Updated February 22, 2017 12:07 PM