digitalist.global // September 30 2016

Create menu items programmatically in Drupal 8

I will go through how to build a menu and menu items that is translatable in code. Let’s say for example we want to rebuild our main menu each time a user saves a node.

 

<?php

use Drupal\menu_link_content\Entity\MenuLinkContent;

function wk_module_node_presave() {
  // The name of our menu
  $menu_name = 'main';

  // Load the MenuLinkManager.
  $menu_handler = \Drupal::service('plugin.manager.menu.link');

  // Delete the existing links in the menu we want to rebuild
  $menu_handler->deleteLinksInMenu($menu_name);

  // Here we are creating the first level and pointing 
  // it to /first_level
  $first_level = MenuLinkContent::create([
      'title' => 'First Level',
      'link' => ['uri' => 'internal:/first_level'],
      'menu_name' => $menu_name,
      'expanded' => TRUE,
  ]);
  // Save the first level
  $first_level->save();

  // Create a array from fake nids for this example's sake. 
  // In a real life scenario you will want to use real data.
  $nids = array(
      '0' => 'Item 1',
      '1' => 'Item 2',
      '2' => 'Item 3'
  );

  foreach($nids as $nid => $title) {
    // When creating the second level of our menu we are 
    // setting the parent value to the id of 
    // our first level menu.
    $second_level = MenuLinkContent::create([
        'title' => title,
        'link' => ['uri' => 'internal:/node/' . $nid],
        'parent' => $first_level->getPluginId(),
        'expanded' => TRUE,
    ]);

    // Create a swedish translation for our menu item
    $second_level->addTranslation('sv', array(
      'title' => t($title))
    );
    // Save our new menu item
    $second_level->save();
  }

}

 

More from digitalist.global