How to Override Block, Controller, and Model in Magento 2

Overriding is one of the most important concepts of Magento 2 because it provides you with the options to change any behavior of the core functionality of the Magento store. See the step-by-step guide to override the class file in Magento 2.

In this article, I am going to explain step by step procedure of overriding the block class and their methods. Also, I will explain how you can rewrite the controller and model class.

Override concept in Magento 2

When we are working in Magento 2 e-commerce, it is said not to rewrite any core files directly. So the best way to change the functionality is to override that core files using the custom modules or using a custom theme.

So here, overriding or rewriting of the block class, controller, or model class files in Magento 2 gives the flexibility to change the core functionality in the custom development requirements.

The controller is basically known as the backbone of the Magento 2 Modules because it's responsible for handling all kinds of incoming requests.

 

How to Override Block Class in Magento 2

This step will help you to rewrite the block class in Magento 2. So in order to rewrite the block first, we have to create a di.xml file: VendorName\ModuleName\etc\di.xml

<?xml version="1.0"?>
<!-- /**
* @category Wishusucess Override Block, Model, Controller
* Website http://www.wishusucess.com/
* @Author: Hemant Singh Magento 2X Developer
*/ -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<preference for="Magento\Swatches\Block\Product\Renderer\Configurable" type="VendorName\ModuleName\Block\Rewrite\Product\Renderer\Configurable" />
</config>

and then create a class file VendorName\ModuleName\Block\Rewrite\Product\Renderer\Configurable to override the Magento block.

Here I have taken an example of a configurable product that's why I am giving the class of configurable block.

<?php
namespace VendorName\ModuleName\Block\Rewrite\Product\Renderer;

class Configurable extends \Magento\Swatches\Block\Product\Renderer\Configurable
{

protected function getRendererTemplate()
{
return $this->isProductHasSwatchAttribute() ?
self::SWATCH_RENDERER_TEMPLATE : 'VendorName_ModuleName::product/view/type/options/configurable.phtml';
}
}

?>

Factory Class: What is Factory Design Pattern in Magento 2

 

Steps for Override Model Class in Magento 2

So here I am giving one example to rewrite a Model class in Magento 2. So firstly we need to create a di.xml file and by giving the preference of the core file we will create another class file for the model.

File Path: VendorName\ModuleName\etc\di.xml

<?xml version="1.0"?>
<!-- /**
* @category Wishusucess rewrite Block, Model, Controller
* Website http://www.wishusucess.com/
* @Author: Hemant Singh Magento 2X Developer
*/ -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<preference for="Magento\ConfigurableProduct\Model\ConfigurableAttributeData" type="VendorName\ModuleName\Model\Rewrite\ConfigurableAttributeData" />
</config>

 

Now, here you have to create the class file which is given VendorName\ModuleName\Model\Rewrite\ConfigurableAttributeData in the di.xml file to override Magento Model.

<?php
/**
* @category Wishusucess rewrite Block, Model, Controller
* Website http://www.wishusucess.com/
* @Author: Hemant Singh Magento 2X Developer
*/ 
namespace VendorName\ModuleName\Model\Rewrite;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Pricing\Helper\Data;

class ConfigurableAttributeData extends \Magento\ConfigurableProduct\Model\ConfigurableAttributeData
{
private $productRepository;
private $priceHelper;

public function __construct(
ProductRepositoryInterface $productRepository,
Data $priceHelper
)
{
$this->productRepository = $productRepository;
$this->priceHelper = $priceHelper;

}

protected function getAttributeOptionsData($attribute, $config)
{
$attributeOptionsData = [];
foreach ($attribute->getOptions() as $attributeOption) {

$optionId = $attributeOption['value_index'];
$product_details = $config[$attribute->getAttributeId()][$optionId];
$productId = $product_details[0];
$product = $this->productRepository->getById($productId);
$attributeOptionsData[] = [
'id' => $optionId,
'label' => $attributeOption['label'],
'products' => isset($config[$attribute->getAttributeId()][$optionId])
? $config[$attribute->getAttributeId()][$optionId]
: [],
'sku' => $product->getSku(),
'childProductPrice' => $this->priceHelper->currency($product->getFinalPrice(), true, false),
];
}
return $attributeOptionsData;
}
}
?>

 

How to Override Controller Class in Magento 2

Now for the model also we have to follow the same procedure as we have followed above for the block and model.

So similarly we will create a di.xml file then we will give the preferences for that.

Magento 2 rewrite controller class:

File Path: VendorName\ModuleName\etc\di.xml

<?xml version="1.0"?>
<!-- /**
* @category Wishusucess Override Block, Model, Controller
* Website http://www.wishusucess.com/
* @Author: Hemant Singh Magento 2X Developer
*/ -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
<preference for="Magento\Catalog\Controller\Product\Gallery" type="VendorName\ModuleName\Controller\Product\Gallery" />
</config>

 

Now here we will create a controller override class file by using the preferences to create a class.

VendorName\ModuleName\Controller\Product\Gallery to rewrite Magento block

<?php
/**
* @category Wishusucess Override Block, Model, Controller
* Website http://www.wishusucess.com/
* @Author: Hemant Singh Magento 2X Developer
*/ 
namespace VendorName\ModuleName\Controller\Product;

class Gallery extends \Magento\Catalog\Controller\Product\Gallery
{

public function execute()
{
$result = null;
if (!$this->_initProduct()) {
$store = $this->getRequest()->getQuery('store');
if (isset($store) && !$this->getResponse()->isRedirect()) {
$result = $this->resultRedirectFactory->create();
$result->setPath('');
} elseif (!$this->getResponse()->isRedirect()) {
// Apply custom code
}
}
return $result ?: $this->resultPageFactory->create();
}
}

Conclusion of Override Steps:

By using the preferences in the di.xml file we can override or overwrite any of the class files of Magento 2. The above code is just an example of how to override the Block, Model, and Controller class of Magento.

 

Recommend Post:

Magento 2.4 Installation Guide: How to Install Magento 2.4.2