Wednesday 13 March 2019

Add Custom Path in Menu item Programmatically

Add Custom Path in Menu item

For this we need following files
  • .routing.yml file
  • .links.menu.yml file
First Register the path in firstcustommodule.routing.yml file as below

firstcustommodule.company_config_form:
  path: '/admin/config/companyconfig'
  defaults:
    _form: '\Drupal\firstcustommodule\Form\CompanyConfigForm'
    _title: 'Add Company Configurations'
  requirements:
    _permission: 'administer site configuration'
1st line: Naming pattern is as module_name.route_name.
Above written code will register path "/admin/config/companyconfig". For this path callback is a CompanyConfigForm class which is placed on firstcustommodule > src > Form. This class will implement Drupal\Core\Form\FormInterface.

Second create a menu item for this path. For this create firstcustommodule.links.menu.yml file.
Now I have to add a menu link in the admin > config then paste below code.
firstcustommodule.company_config_form:
  title: 'Company config settings'
  description: 'Configure company settings'
  route_name: 'firstcustommodule.company_config_form'
  parent: system.admin_config
  weight: 10

Explanation for above lines
First line is reserving namespace as in routing file.
route_name: Here we use namedspace from 1st line of routing.yml file.
Title & Description: These will be displayed in the Development section. 
parent: this describes the parent link for the menu means menu link will be created under its value. For this case parent link is "system.admin_config". We can create links under admin, coding, development etc.

Now clear cache. Link is available as in screenshot.












No comments:

Post a Comment