Dedicated Magento 2 Blog

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

Using Preference

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.

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.

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.

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