How to override a block/model in Magento 2

In this tutorial, I will explain you how to override a block/model in Magento 2.

The following steps are:

Step 1: Override a block

Override catalog product block

Form di.xml file in app/code/[Name_Space]/[Your_Module]/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\Catalog\Block\Product\ListProduct" type="[Name_Space]\[Your_Module]\Block\Rewrite\Product\ListProduct" />

</config>

Create ListProduct.php Block file in app/code/[Name_Space]/[Your_Module]/Block/Rewrite/Product

<?php

   namespace [Name_Space]\[Your_Module]\Block\Rewrite\Product;

   class ListProduct extends \Magento\Catalog\Block\Product\ListProduct

   {

       public function _getProductCollection()

       {

       }

   }

Step 2: override a model

Override a catalog product model

Form di.xml file in app/code/[Name_Space]/[Your_Module]/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\Catalog\Model\Product" type="[Name_Space]\[Your_Module]\Model\Rewrite\Catalog\Product" />

</config>


Form Product.php Model file in 

app/code/[Name_Space]/[Your_Module]/Model/Rewrite/Catalog

<?php

   namespace [Name_Space]\[Your_Module]\Model\Rewrite\Catalog;

   class Product extends \Magento\Catalog\Model\Product

   {

       public function is Scalable()

       {


       }


   }

Last Update: April 7, 2018  

March 3, 2018   359   Nandini Ramachandran    Operations    
Total 2 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn