How to Override Custom Module’s Controller file in Magento 2

Overriding Custom modules controller in Magento2

Understanding that each business has its own story, to give a personalized touch to store always ends up with customization & development. Over the time Magento has topped Ecommerce CMS list with its functionality, features and power of extending the native functionalities. Compared to Magento 1, In Magento 2 overriding and manipulating with classes is becoming easier a developer to play quickly. At MageComp, we have never recommended modifying default core functionalities, but we can extend core functionalities using concepts of overriding which is a safe and easy way to achieve customization or development.

Magento 2 Speed & Performance Optimization Services

The extension plays an important role to achieve customization in Magento 2 but when there are tons of extensions installed within a store environment it creates conflicts with other extensions. At that time to quickly get rid of the problem, the easiest solution comes to mind is to override custom extension controller file. By default, there are three different ways to override core functionalities. Today we will use preference method to override any custom module controller into your extension.

hyva theme development

Step 1: First, we need to create “di.xml” file inside extension the below directory

app\code\Vendor\Extension\etc

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Customvendor\Customextension\Controller\Adminhtml\Customcontroller\Customaction" type="Vendor\Extension\Controller\Adminhtml\Customcontroller\Customaction" />
</config>

Step 2: after that, you need to create “Customaction.php” file inside extension the below directory

app\code\Vendor\Extension\Controller\Adminhtml\Customcontroller

<?php 
namespace Vendor\Extension\Controller\Adminhtml\Customcontroller;
use Magento\Backend\App\Action\Context;

class Customaction extends \Customvendor\Customextension\Controller\Adminhtml\Customcontroller\Customaction
{
public function __construct(Context $context)
{
// YOU NEED TO PASS ALL THE OBJECT WHICH USER BY PARENT CONTROLLER CONSTRUCT FUNCTION.
parent::__construct($context);
}
protected function Customaction()
{
// ADD YOUR CUSTOM CODE HERE
}
}

If you face any issue while implementing this code comment down below. We will help you to fixed it asap. Happy Coding!

Hire Magento Programmer
Previous Article

How to Get Product Image URL in Magento 2

Next Article

Quick Overview of Clutch - a digital Marketplace & Our Profile Reviews

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨