How to create menu link programmatically in drupal 8 & 9
If you would like to create module-defined menu links, add something like this example to your MODULENAME.links.menu.yml file:
example.admin:
title: 'Example Link'
description: 'Description link'
route_name: example.route_name
weight: 10
enabled: 0
route_parameters: { key: 'value' }
menu_name: account
options:
query:
uid: 1
attributes:
target: _blank
class:
- btn
- btn-primary
Example how to use anchor links
example.anchor:
title: "Contact"
description: "Scroll to contact section"
url: "internal:#contact"
Example 2:
In order to create a menu item automatically this can be placed in a hook_update_N
on the file MODULENAME.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();