:::: MENU ::::

Magento 2 overriding Rewriting block

Magento 2 overriding or Rewriting block

Today we talk about Magento 2 overriding Rewriting block. In our daily coding routine we need to customization with core files. For that we need to overriding or rewrite the core classes because modify the core classes is not good practice. If you modify the code classes when you update the new version your code will be loss. So today we learn how to override core blocks. In start we are overriding core Product blocks. We are just checking our rewrite is working or not. You can modify the blocks as you want by following this tutorial. But first you need to know How to create module in Magneto 2.For any suggestions & question, please feel free to drop a comment.

Overriding or Rewrite Magento 2 Block

A Block is one of the first class elements in the structure of Magento layouts. Every page in Magento is decorated by the Layouts file and the content is filled up by the Blocks of the different modules.Now we start to overriding or rewriting core Product block. The model we are overriding is Product Listing block. Magento 2 use block for category product listing.

Step 1.

Create a di.xml file in a following directory QaisarSatti/HelloWorld/etc/

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Block\Product\ListProduct" type="QaisarSatti\HelloWorld\Block\Rewrite\Product\ListProduct" />

Step 2
The step2 to overriding or rewriting Magento 2 block is to create a ListProduct.php block file in the following directory QaisarSatti/HelloWorld/Block/Rewrite/Product

* Catalog Product Rewrite Block
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti

namespace QaisarSatti\HelloWorld\Block\Rewrite\Product;
class ListProduct extends \Magento\Catalog\Block\Product\ListProduct
public function __construct() {

echo "Block Rewrite Working"; die();

As following this code you can rewrite or override any Magento 2 block using the same method.

Give A Rating

Average Rating / 5. Vote Count

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


So, what do you think ?