n How to create menu link programmatically in drupal 8 & 9 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

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:

  title: 'Example Link'
  description: 'Description link'
  route_name: example.route_name
  weight: 10
  enabled: 0
  route_parameters: { key: 'value' }
  menu_name: account 
      uid: 1
      target: _blank
        - btn
        - btn-primary


  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,


You can also create an entire Menu programmatically:

    'id' => 'menu_test',
    'label' => 'Test menu',
    'description' => 'Description text',

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook