In this blog post we will see how to add a menu item in backend for your Magento 2 module.
Contents
The admin menu in Magento 2 has 3 parts:
- The main admin menu title which shows up in left sidebar
- Submenu title
- Actual menu
1 2 3 4 5 6 7 8 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd"> <menu> <add id="VendorName_ModuleName::hello" title="Hello" module="VendorName_ModuleName" sortOrder="15" dependsOnModule="VendorName_ModuleName" resource="VendorName_ModuleName::hello"/> <add id="VendorName_ModuleName::hello_world" title="World" module="VendorName_ModuleName" sortOrder="10" parent="VendorName_ModuleName::hello" resource="VendorName_ModuleName::hello" /> <add id="VendorName_ModuleName::hello_world_test" title="Test1" module="VendorName_ModuleName" sortOrder="10" parent="VendorName_ModuleName::hello_world" action="hello/world" resource="VendorName_ModuleName::hello_world_test"/> </menu> </config> |
2. Create file VendorName/ModuleName/etc/acl.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> <acl> <resources> <resource id="Magento_Adminhtml::admin"> <resource id="VendorName_ModuleName::hello" title="Hello" sortOrder="20"> <resource id="VendorName_ModuleName::hello_world" title="World" sortOrder="10"> <resource id="VendorName_ModuleName::hello_world_test" title="Test1" sortOrder="10"> </resource> </resource> </resource> </resource> </resources> </acl> </config> |
3. Create Admin Routes with file: VendorName/ModuleName/etc/adminhtml/routes.xml
with content:
1 2 3 4 5 6 7 8 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd"> <router id="admin"> <route id="hello" frontName="hello"> <module name="VendorName_ModuleName" /> </route> </router> </config> |
VendorName/ModuleName/Controller/Adminhtml/World/Index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace VendorName\ModuleName\Controller\Adminhtml\World; class Index extends \Magento\Backend\App\Action { public function __construct( \Magento\Backend\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory ) { parent::__construct($context); $this->resultPageFactory = $resultPageFactory; } public function execute() { echo "Hello World"; exit; } } |
Finally, when you click on the new menu item, you will see “Hello World” in a page.
If something is wroing, you will be redirected to dashboard automatically.
That’s how to add a menu item in backend Magento 2, see you in other posts.