Drupal - How do I create menu links programmatically?

In order to create a menu item automatically this can be placed in a hook_update_N on the file mymodule.install and will run when the database is updated (/update.php):

use Drupal\menu_link_content\Entity\MenuLinkContent;
$items = array(
  '1' => 'Menuitem 1',
  '2' => 'Menuitem 2',
  '3' => 'Menuitem 3'
);

foreach($items as $nid => $title) {
  $menu_link = MenuLinkContent::create([
    'title' => $title,
    'link' => ['uri' => 'internal:/node/' . $nid],
    'menu_name' => 'main',
    'expanded' => TRUE,
  ]);
  $menu_link->save();
}

You can also create an entire Menu programmatically:

\Drupal::entityTypeManager()
  ->getStorage('menu')
  ->create([
    'id' => 'menu_test',
    'label' => 'Test menu',
    'description' => 'Description text',
  ])
  ->save();

If you would like to create module-defined menu links, add something like this example to your custom_module.links.menu.yml file:

custom_module.admin_item_1:
  title: 'New Admin Item 1'
  parent: system.admin
  description: 'Description of link goes here.'
  route_name: view.some_view_id.page_1

parent (optional) is the id column of the parent in the menu_tree table, and route_name is Drupal's internal route ID for where you'd like the menu item to link to. It's in the menu_tree table as route_name.

See Providing module-defined menu links and Add a menu link for more details and options.

Tags:

Navigation

8