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:

Code snippet that can be used to create menu link programmatically in drupal 8.

to add menu links juste use MenuLinkContent::create() function where you want.

Here an example with custom menu link:

use Drupal\menu_link_content\Entity\MenuLinkContent;

/**
 * hook_cron()
 */
function mymodule_cron(){

  MenuLinkContent::create([
    'title' => 'Contact US',
    'link' => ['uri' => 'internal:/node/2'],
    'menu_name' => 'main',
    'weight' => 10,
  ])->save();
}

Here an example with submenu creation:

juste add 'parent' option.

'parent' => 'route.name',

Or you can use this example:

$menu_link_content = MenuLinkContent::create([
  'title' => 'Menu',
  'link' => ['uri' => 'internal:/node/2'],
  'menu_name' => 'main',
  'weight' => 2,
  'expanded' => TRUE,
]);
$menu_link_content->save();

$mid = $menu_link_content->getPluginId();
$menu_link_2 = MenuLinkContent::create([
  'title' => 'Submenu',
  'link' => ['uri' => 'internal:/node/3'],
  'menu_name' => 'main',
  'weight' => 21,
  'parent' => $mid,
]);
$menu_link_2->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