Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Programmatically create a menu link in Drupal 8
@yukare

This comment has been minimized.

Copy link

@yukare yukare commented Jan 28, 2017

How can i create a menu link that is child of other menu link ?

@sawtell

This comment has been minimized.

Copy link

@sawtell sawtell commented Jun 17, 2017

You need to provide a parent plugin ID.
e.g.

use Drupal\menu_link_content\Entity\MenuLinkContent;
// $parent_link = Drupal\menu_link_content\Plugin\Menu\MenuLinkContent
MenuLinkContent::create([
  'title' => 'Hello World',
  'link' => ['uri' => 'internal:/node'],
  'menu_name' => 'main',
  'weight' => 10,
  'parent' => $parent_link->getPluginId(),
])->save();

To get the parent MenuLinkContent link item, look at the plugin.manager.menu.link or menu.link_tree services

@GolubovicM

This comment has been minimized.

Copy link

@GolubovicM GolubovicM commented Sep 10, 2018

Where that code should be placed so it's executed only once? Also, what about translatable menu items? How to add menu item that has different title and url (path) for different languages?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment