Drupal - How do I programmatically update or delete menu items?

First you will have to load the entity. Either way works:

$menu_link = MenuLinkContent::load($menu_link_id);

or ...

$menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($menu_link_id);

Next you can update value using set() method or through the magic method __set...

$menu_link->expanded = TRUE;

To save, simply call the save() method. To delete, simply call the delete() method.


I had to do some thing like ....

 
 //menuLinkManager = 'plugin.manager.menu.link'
$result = $this->menuLinkManager->loadLinksByRoute('entity.node.canonical', ['node' => $node->id()]);
foreach ($result as $menu_item) {
          if (is_object($menu_item)) {
            $id = $menu_item->getPluginDefinition()['metadata']['entity_id'];
$menu_link = $this->entityTypeManager->getStorage('menu_link_content')->load($id);
$menu_link->enabled = 0;
$menu_link->save()

Tags:

Navigation

8