Overriding Controller, Block, Model and Helper In Magento 2 Using Preference

Overriding Controller, Block, Model and Helper In Magento 2 Using Preference

It is very important to understand override in Magento 2 framework, especially when you are going to rewrite specific functionality to full fill the custom need of the project. In Magento 1 override is possible by rewrites. You can rewrite any class in your custom module and insert your custom code.

In Magento 2 Override can be achieved by two methods. Those methods are

  1. Using Preference
  2. Using Plugin

In this article, we are going to see overriding Controller, Block, Model and Helper using Preference. Before we start let’s create basic module files.

Module Setup

app/code/Codextblog/Customoverride/etc/module.xml – This file is a module configuration file.

app/code/Codextblog/Customoverride/registration.php – This file is module registration file that register our module in magento 2 system.

app/code/Codextblog/Customoverride/etc/di.xml – This file define all the rewrite configuration.

app/code/Codextblog/Customoverride/Controller/Customer/Account/Index.php – This is our custom controller file which override the core “Customer” controller file.

app/code/Codextblog/Customoverride/Block/Customer/Sidebar.php – This is our custom block file which override the core wishlist sidebar block file.

app/code/Codextblog/Customoverride/Model/Catalog/Product.php – This is our custom model file which override the core “Catalog” model file.

app/code/Codextblog/Customoverride/Helper/Catalog/Data.php – This is our custom helper file which override the core “Catalog” helper file.

Getting Started: Development

Step 1: Create module.xml file under app/code/Codextblog/Customoverride/etc directory

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Codextblog_Customoverride" setup_version="1.0.0"></module>
        <sequence>
            <module name="Magento_Backend"/>
             <module name="Magento_Sales"/>
            <module name="Magento_Quote"/>
            <module name="Magento_Checkout"/>>
        </sequence>
</config>

Step 2: Create registration.php file under app/code/Codextblog/Customoverride directory

<?php
 
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Codextblog_Customoverride',
    __DIR__
);

Override Controller

We will override the core “Customer” module Account’s Index.php file and change the page title to “My Dashboard”. If you visit the customer account page (www.example.com/customer/account/) in your Magento site, you find that page title is set to “My Account”. This title is set from /vendor/magento/module-customer/Controller/Account.php file. We will override this file under our custom module and change the page title to “My Dashboard”.

To override controller file in Magento 2 we need to create di.xml file. This file define the rewrite of classes.

Step 3: Create di.xml file under app/code/Codextblog/Customoverride/etc directory

<?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\Customer\Controller\Account\Index" type="Codextblog\Customoverride\Controller\Customer\Account\Index" />
</config>

By using preference we have override core module file with our custom module. Here we have passed the core file path to “for” parameter and custom file path to “type” parameter in <preference> tag. This is how Magento 2 identify which class to override.

Step 4: Now let’s create our custom controller file Index.php under app/code/Codextblog/Customoverride/Controller/Customer/Account directory

<?php
namespace Codextblog\Customoverride\Controller\Customer\Account;

class Index extends \Magento\Customer\Controller\Account\Index
{ 
    public function execute()
    {
        /** @var \Magento\Framework\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('My Dashboard'));
        return $resultPage;
    }
    
}

We have defined the class Index which is extending Class \Magento\Customer\Controller\Account\Index. In Magento 1 when we extend controller file we have to include the core file before extend, In Magento 2 we don’t require to do that as Magento 2 automatically included core file.

We have copied the execute method from core file and just change the title to “My Dashboard” at line no. 10. So whenever you visit the customer account page on frontside, Magento 2 will execute the execute() method from our custom controller and only this code is going to take effect.

Override Block

We will override the core getTitle function of class \Magento\Wishlist\Block\Customer\Sidebar and change the default title of wishlist sidebar block

Step 5: Add the preference tag for block file in di.xml file

<?xml version="1.0"?>
 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> 

	<!--Controller override  -->   
    <preference for="Magento\Customer\Controller\Account\Index" type="Codextblog\Customoverride\Controller\Customer\Account\Index" />
    
    <!--Block override  -->
    <preference for="Magento\Wishlist\Block\Customer\Sidebar" type="Codextblog\Customoverride\Block\Customer\Sidebar" />
    
</config>

Step 6: Create Sidebar.php file under app/code/Codextblog/Customoverride/Block/Customer directory and paste the below code

<?php
namespace Codextblog\Customemail\Block\Customer;

class Sidebar extends \Magento\Wishlist\Block\Customer\Sidebar
{
    
    /**
     * Retrieve block title
     *
     * @return \Magento\Framework\Phrase
     */
    public function getTitle()
    {
        //return __('My Wish List');
        return __('Wish List');
    }
    
    
}

When you visit the sidebar of My Account Page, You can see that wishlist sidebar block title is changed to “Wish List” from “My Wish List”

Override Model

We will override the core getSku function of class \Magento\Catalog\Model\Product and append the custom string to sku

Step 7: Add the preference tag for model file in di.xml file

<?xml version="1.0"?>
 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> 

	<!--Controller override  -->   
    <preference for="Magento\Customer\Controller\Account\Index" type="Codextblog\Customoverride\Controller\Customer\Account\Index" />
    
    <!--Block override  -->
    <preference for="Magento\Wishlist\Block\Customer\Sidebar" type="Codextblog\Customoverride\Block\Customer\Sidebar" />

    <!--Model override  -->
    <preference for="Magento\Catalog\Model\Product" type="Codextblog\Customoverride\Model\Catalog\Product" />
    
</config>

Step 8: Create Product.php file under app/code/Codextblog/Customoverride/Model/Catalog directory and paste the below code

<?php
namespace Codextblog\Customoverride\Model\Catalog;

class Product extends \Magento\Catalog\Model\Product
{
    
    public function getSku()
    {
        return "Custom-".$this->getTypeInstance()->getSku($this);
    }
}

When you visit the Product view page, You found that SKU is appended with string “custom-“. For example, SKU called WT09 is displayed as a custom-WT09.

Override Helper

We will override the core getProduct function of class \Magento\Catalog\Helper\Data and print the log file.

Step 9: Add preference tag for helper in di.xml file

<?xml version="1.0"?>
 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> 

	<!--Controller override  -->   
    <preference for="Magento\Customer\Controller\Account\Index" type="Codextblog\Customoverride\Controller\Customer\Account\Index" />
    
    <!--Block override  -->
    <!-- <preference for="Magento\Catalog\Block\Product\View" type="Codextblog\Customoverride\Block\Catalog\Product\View" /> -->
    
    <preference for="Magento\Wishlist\Block\Customer\Sidebar" type="Codextblog\Customoverride\Block\Customer\Sidebar" />
    
    
    <!--Model override  -->
    <preference for="Magento\Catalog\Model\Product" type="Codextblog\Customoverride\Model\Catalog\Product" />
    
    
    <!--Helper override  -->
    <preference for="Magento\Catalog\Helper\Data" type="Codextblog\Customoverride\Helper\Catalog\Data" />
    
</config>    

Step 10: Create Data.php file under app/code/Codextblog/Customoverride/Helper/Catalog directory and paste the below code

<?php
namespace Codextblog\Customoverride\Helper\Catalog;

class Data extends \Magento\Catalog\Helper\Data
{
 
    public function getProduct()
    {
        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug('Custom helper function');
        
        return $this->_coreRegistry->registry('current_product');
    }
}

You can see the log printed under var/log/debug.log file

[2017-12-06 05:15:35] main.DEBUG: Custom helper function {"is_exception":false} []

If you liked this post, then please like us on Facebook and follow us on Twitter.

Want to ask a question or leave a comment?

Leave a Comment

(1 Comment)

  • LalitaPrasad Sahoo

    Awesome, you make it very simple understand Magento2. It make me understand the topic as you are writing every topic by comparing it with its previous Magento1 verson.

  • All the comments are goes into moderation before approval. Irrelevant comment with links directly goes to spam. Your email address will not be published.

    Was this post helpful? Please support Us!

    Follow us on twitter or Like us on facebook.

     


    To Avoid Spam Downloads, We Want Your Email

    We will send you download link right
    away. Please submit form below.
    SEND ME DOWNLOAD LINK
    Close

    Increase Your
    Magento 2
    Knowledge

    Get Weekly Tutorial
    to your Inbox
    Subscribe Me
    close-link
    Subscribe Here