digitalist.global // May 09 2016

Creating menu links in Drupal 8, two different approaches

In you header of your file, for me this my_module.install, add:

use Drupal\Core\Menu\MenuLinkManager;

Here I am creating a menu link in the main menu, pointing on a internal link – a taxonomy term page

mymodule_update_8101() {
  // Create a new menu item.
  MenuLinkContent::create([
    'title' => 'My term',
    'link' => ['uri' => 'internal:/taxonomy/term/3'],
    'menu_name' => 'main',
  ])->save();
}

This creates an editable menu link, with the title ‘My term’ that could be changed in the Drupal UI whoever have permission to do so, but if you want to have a menu item that should not be altered in the UI, you could create a meny.yml file (in my case mymodule.links.menu.yml) with your entry.

mymodule.inspiration:
  title: 'My term'
  url: 'internal:/taxonomy/term/3'
  menu_name: main
  weight: 12

I prefer the last solution, that make menu links that should always be on the site version controlled. Also, titles in yml-files is automatically translatable. See my colleague Jonathans post about translatable Menu items if you are using the first approach.

Also you you could easily point to mymodule.inspiration in other places in the code, I will look at that in my next blog post.

More from digitalist.global