Controller Override in Magento 2

  • author-img Nidhi Arora
  • 5 years
  • 604 views
Controller Override in Magento (2)

Today, we’re going to explain how to override controller in Magento 2 and hope you are already familiar with controller & its functionality. Controller basically stands behind the process of handling incoming requests and it plays a significant role in Magento 2 routing implementation. Controller overriding is mainly required while working on custom modules in Magento 2 and you need to work on overriding core module files.

By following the simple steps as mentioned below, you can easily override the controller in Magento 2 and we hope that you can grab that “Ah-ha!” moment. Or at the very least you’ll say, “That’s very easy.”

Step1)

Create di.xml file in app/code/<VendorName>/<ModuleName>/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="Magento\Checkout\Controller\Cart\Add" type="<VendorName>\<ModuleName>\Controller\Rewrite\Cart\Add" />

 

</config>

 

Code Explanation

<VendorName>\<ModuleName>\Controller\Rewrite\Cart\Add is used to override Magento\Checkout\Controller\Cart\Add

Step2)

Define an overriding controller class

Create Add.php in app/code/<VendorName>/<ModuleName>/Controller/Rewrite/Cart/


<?php


namespace <VendorName>\<ModuleName>\Controller\Rewrite\Cart;


class Add extends \Magento\Checkout\Controller\Cart\Add

{

public function execute()

{

// perform action

}

}

Download Blog

ENQUIRY

Ready to Get started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    1250 Pittsford Victor Road Ste 310
    Pittsford, NY 14534

    Development Center

    Plot no. 10, Rajiv Gandhi
    Chandigarh Technology Park