I have seen the post on how to create menu items programmatically in Drupal 8, but how do I update or delete menu items in D8?
Clarification: by programmatically I mean dynamically so yaml config files are not going to help.
I have seen the post on how to create menu items programmatically in Drupal 8, but how do I update or delete menu items in D8?
Clarification: by programmatically I mean dynamically so yaml config files are not going to help.
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()
Probably too late I did like:
$menu_handler = \Drupal::service('menu.link_tree')
->load("menu-name", new \Drupal\Core\Menu\MenuTreeParameters());
foreach($menu_handler as $key=>$value) {
if('Name' == $value->link->getTitle()) {
$link = $value->link;
$link->updateLink(
[
'enabled'=>'1',
'title'=>'New Name'
],
true
);
}
}