Drupal 8 Menu System | Drupal 8

Drupal 8 Menu System

Submitted by editor on Mon, 11/23/2015 - 12:45
Question
  1. How to add a menu item
  2. How to add a sub item/tab/menu task
  3. How to add configuration Link
  4. How to create menu links to external URL

1. Define route in module.routing.yml
Exemple :
module.view.settings:
  path: '/url/to/the/page'
  defaults:
    _controller: '\Drupal\module\Controller\Demo::view'
    _title: ''
  requirements:
     _role: 'authenticated+admin'

module.view.tab2:
  path: '/url/to/the/page2'
  defaults:
    _controller: '\Drupal\module\Controller\Demo::view'
    _title: ''
  requirements:
     _role: 'authenticated+admin'

2. Create menu item in module.links.menu.yml
Exemple:
module.view:
  title: 'Demo View'
  description: 'Just for demo'
  parent: system.admin_reports
  route_name: module.view.settings

3. Create sublink / menu task / Tab
Exemple:
module.tab1:
  route_name: module.view.settings
  title: 'Tab 1'
  base_route: module.view.settings

module.tab2:
  route_name: module.view.tab2
  title: "Tab 2"
  base_route: module.view.settings

 

To add  the configuration path to a module.
add to the module.info.yml:
configure: route.name
Exemple:
configure: module.view.settings

 

Arguments:

Example:
mymodule.test.testarg:
  path: '/test/{testarg}'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
    _title: 'Test'
    testarg: index
  options:
    parameters:
      testarg:
        type: String

Add url arguments (Route parameters) to a menu item.

mymodule.the_menu_id:
  title: 'The Title'
  menu_name: tools
  route_name: mymodule.myroute
  route_parameters: { id: 'en' }

Note : If the name of the route parameter is defined in the path, this will replace the default value. Otherwise it will added as a $_GET argument
Like (for previous example) :
  ...
  route_name: mymodule.test.testarg
  route_parameters:

    testarg: 'test' # Will be '/test/{test}'
    name: 'value' # Will be '/test/{test}?name=value'

 

Arguments types:
testarg: Y|N
testarg: \d+

testarg: node
testarg: String

...

 

Other Examples

Views pages route : view.VIEW_ID.DISPLAY_ID
Views Menu Id : views_view:views.VIEW_ID.DISPLAY_ID
Add Menu item to a views

Views route name : view.VIEW_ID.DISPLAY_ID
Example (Route) : view.content.page_1 For the Content page view
Example (Default Menu) : views_view:views.content.page_1 For the Content page view
You can use this route on a MODULE.links.menu.yml, MODULE.links.action.yml ...

Create menu links to external URL

Example:
mymodule.tools.drupal8:
  title: 'Drupal 8'
  description: 'Drupal8.ovh web site'
  url: 'https://www.drupal8.ovh'
  menu_name: tools
  weight: -1
  options:
    attributes:
      target: _blank
      class: my-class

 

More info : https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

Add new comment