This post walks through the process to override an admin controller in Magento 2. Code is available at https://github.com/dbsdsun/magento2Override.
There are a few steps to override a Magento 2 controller.
- Building a Magento 2 extension structure
- Setting preference in di.xml
- Defining an overriding controller class
Step 1. Building a Magento 2 extension structure
Building directories as following:
magento2 --- app --- code
|--- Sample --- HelloWorld
| --- Controller
| --- etc
| --- module.xml
| --- di.xml
Creating module.xml to define a Magento2 extension:
<?xml version="1.0"?>
<!--
/**
* Created by wilson.sun330@gmail.com
* Date: 11/09/2015
* Time: 5:02 PM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Sample_HelloWorld" setup_version="0.0.1"/>
</config>
Step 2. Setting preference in di.xml
Creating di.xml to refer the overriding class:
<?xml version="1.0"?>
<!--
/**
* Created by wilson.sun330@gmail.com
* Date: 11/09/2015
* Time: 5:02 PM
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Controller\Adminhtml\Product\Edit" type="Sample\HelloWorld\Controller\Catalog\Adminhtml\Product\Edit" />
</config>
Sample\HelloWorld\Controller\Catalog\Adminhtml\Product\Edit will be used to override Magento\Catalog\Controller\Adminhtml\Product\Edit, which is the product edit controller for admin in original Magento 2.
Step 3. Defining an overriding controller class
Under magento2/app/code/Sample/HelloWorld/Controller/Catalog/Adminhtml/Product, defining Edit.php as following.
<?php
/**
* Created by wilson.sun330@gmail.com
* Date: 11/09/2015
* Time: 5:02 PM
*/
namespace Sample\HelloWorld\Controller\Catalog\Adminhtml\Product;
class Edit extends \Magento\Catalog\Controller\Adminhtml\Product\Edit
{
public function execute()
{
$this->messageManager->addSuccess('Message from new admin controller.');
return parent::execute();
}
}
Edit.php redefines function execute() to override the function in \Magento\Cms\Controller\Adminhtml\Product\Edit. The new execute() adds a message to product edit page, but it may also implements a complex logic.