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
Category:

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.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();

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon