Today we discuss how in magento 2 create admin controller. This tutorial include the basic structure of admin controller and how to execute and create admin controller. Now we start with our example.
For the creating custom admin controller first create the route routes.xml file in following directory to access to admin controller.
QaisarSatti/HelloWorld/etc/adminhtml/
<?xml version="1.0"?>
<!--/**
* Hello World
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/ -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="helloworld" frontName="helloworld">
<module name="QaisarSatti_HelloWorld" before="Magento_Backend" />
</route>
</router>
</config>
<!--/**
* Hello World
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/ -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="helloworld" frontName="helloworld">
<module name="QaisarSatti_HelloWorld" before="Magento_Backend" />
</route>
</router>
</config>
Now create the admin controller. Index.php in following directory
QaisarSatti\HelloWorld\Controller\Adminhtml\Index
<?php
/**
* Hello World
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/
namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;
class Index extends \Magento\Backend\App\Action
{
protected $resultPageFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
public function execute()
{
echo "My admin controller"; exit;
}
protected function _isAllowed()
{
return true;
}
}
/**
* Hello World
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/
namespace QaisarSatti\HelloWorld\Controller\Adminhtml\Index;
class Index extends \Magento\Backend\App\Action
{
protected $resultPageFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Registry $coreRegistry,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context, $coreRegistry);
}
public function execute()
{
echo "My admin controller"; exit;
}
protected function _isAllowed()
{
return true;
}
}
Note: This is basic example how to create custom admin controller