Skip to content

Instantly share code, notes, and snippets.

@shadcn
Last active September 10, 2018 09:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadcn/fbc536e3c1587a35e02068f088d56a91 to your computer and use it in GitHub Desktop.
Save shadcn/fbc536e3c1587a35e02068f088d56a91 to your computer and use it in GitHub Desktop.
Programmatically create a menu link in Drupal 8
@yukare
Copy link

yukare commented Jan 28, 2017

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

@sawtell
Copy link

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
Copy link

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