Overriding a block in Magento 2

In each Magento project, there is always a certain level of customization required, which can involve adding entirely new elements or overriding the existing ones. Customizing your Magento store according to your preferences not only gives you a personalized feel and ease of use while handing tasks but also improves the customer user experience in several levels that can benefit your business with increased conversions and revenues. Besides completely modifying core files, Magento recommends to override the core files if needed.

There are few steps to override a block in Magento 2

Step 1: Build a Magento 2 extension structure

  • Build directories:
magento2 --- app --- code

                      |--- Sample --- HelloWorld

                                             | --- Block

                                             | --- etc

                                                   | --- module.xml

                                                  | --- di.xml
  • Create module.xml to define a Magento 2 extension:
<?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="Sample_HelloWorld" setup_version="0.0.1"/>

</config>

Step 2: Set preference in di.xml

  • Create di.xml to refer the overriding block class:
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">  

<preference for="Magento\Theme\Block\Html\Title" type="Sample\HelloWorld\Block\HelloTitle" />

</config>

Step 3: Define an overriding class

  • Define HelloTitle.php under magento2/app/code/Sample/HelloWorld/Block:
<?php

namespace Sample\HelloWorld\Block;

use Magento\Framework\View\Element\Template;

class HelloTitle extends \Magento\Theme\Block\Html\Title

{
   public function getPageTitle()
   {
      return 'haha9999';
   }  

   protected function _toHtml()
   {
      $this->setModuleName($this->extractModuleName('Magento\Theme\Block\Html\Title'));      

      return parent::_toHtml();
   }
}

That’s all. Overriding block in Magento 2 is an easy tutorial so we think that all of you can perform it. If you want more tutorial about Magento 2, let’s access our blog to get them.

Thanks for reading!