Thursday 27 April 2017

Drupal 8 Create a menu and add menu link in admin menu

In drupal 7 it is a very simple task because hook_menu provides the straightforward implementation but in drupal 8 its implementation is very different. In drupal 8 we create the YAML files. Hook menu is converted into routing file.
So let us take an example to understand this. We want to add a link under the admin -> configuration -> search and metadata.
So for this first, we have to create a menu link(In D8 routing)

Create a file  (My_Module.routing.yml) under your module directory.

My_Module.MY-MENU:
  path: '/admin/config/search/MY-PATH'
  defaults:
    _form: 'Drupal\My_Module\Forms\MYMENU'
    _title: 'MY MENU'
  requirements:
    _permission: 'administer site configuration'

Here My_Module.MY-MENU it is unique machine name. For more detail click here

So above code just registers your menu in the menu configuration. After clearing cache you will be able to visit  URL directly. It works fine if you haven't made any mistake in defining controllers. To listing  this URL into admin menu we have to implement following code
Create another file in the same directory (My_Module.links.menu.yml)

My_Module.MY-MENU:
  title: 'MY MENU NAME'
  parent: system.admin_config_search
  description: 'Add MY path'
  route_name: My_Module.MY-MENU:
  weight: -1

Here My_Module.MY-MENU this can be different but for our convenience, we provide the same routing machine name.
 parent : For parent, we need to search routing machine name of parent menu (In our case parent menu is admin -> configuration -> search and metadata ). Mostly you can find these paths into routing.yml files.

No comments:

Post a Comment

Thanks!