cancel
Showing results for 
Search instead for 
Did you mean: 

Overriding a block in Magento 2

Overriding a block in Magento 2

Overriding a block in Magento 2
May 22, 2015 · by Wilson.sun330@gmail.com

 

This post walks through the process to extend a block in Magento 2. Code is available at https://github.com/dbsdsun/magento2Override .


There are a few steps to override a Magento 2 block.

 

  1. Building a Magento 2 extension structure
  2. Setting preference in di.xml
  3. Defining an overriding class


Step 1. Building a Magento 2 extension structure

 

Building directories as following:

 

magento2 --- app --- code
                       |--- Sample --- HelloWorld
                                             | --- Block
                                             | --- etc
                                                    | --- module.xml
                                                    | --- di.xml

 

Creating module.xml to define a Magento2 extension:

<?xml version="1.0"?>
<!--
/**
 * Created by wilson.sun330@gmail.com
 * Date: 13/05/2015
 * Time: 5:02 PM
 */
-->
<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. Setting preference in di.xml

Creating di.xml to refer the overriding block class:

<?xml version="1.0"?>
<!--
/**
 * Created by wilson.sun330@gmail.com
 * Date: 13/05/2015
 * Time: 5:02 PM
*/
-->
<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>

Sample\HelloWorld\Block\HelloTitle will be used to override Magento\Theme\Block\Html\Title.


Step 3. Defining an overriding class

 

Under magento2/app/code/Sample/HelloWorld/Block, defining HelloTitle.php as following.

<?php
/**
 * Created by wilson.sun330@gmail.com
 * Date: 13/05/2015
 * Time: 5:02 PM
 */
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();
    }
}


HelloTitle.php redefines function getPageTitle() to override the function in \Magento\Theme\Block\Html\Title. The new getPageTitle() just return a text string, but it may also implements a complex logic. 


HelloTitle.php also redefines function _toHtml(). Although HelloTitle overrides \Magento\Theme\Block\Html\Title, the template file of \Magento\Theme\Block\Html\Title is still supposed to be used. And the real path of a template file is determined by both the module name of a block and the template attribute of the block. Therefore, the module name of HelloTitle is still Magento_Theme, rather than Sample_HelloWorld.

 

This line

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


sets the correct nominal module name. This module name is necessary to render with the template originally defined for Magento\Theme\Block\Html\Title.

Tags (1)
4 REPLIES

Re: Overriding a block in Magento 2

Any one know how can i get category id using current category registry in magento 2?

 

i need current category id in tolbar block.

 

Thanks

Tags (1)

Re: Overriding a block in Magento 2

Thanks by your explanation.

 

About 

 

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

 

Checking Magento code the setModuleName is required because the /lib/internal/Magento/Framework/View/FileSystem.php::getTemplateFileName() uses the module name to get the template file defined in module.

 

    public function getTemplateFileName($fileId, array $params = [])
    {
        list($module, $filePath) = \Magento\Framework\View\Asset\Repository::extractModule(
            $this->normalizePath($fileId)
        );
        if ($module) {
            $params['module'] = $module;
        }
        $this->_assetRepo->updateDesignParams($params);
        return $this->_templateFileResolution
            ->getFile($params['area'], $params['themeModel'], $filePath, $params['module']);
    }

 

Best wishes

Re: Overriding a block in Magento 2

Thanks for this amazing tutorial as i am doing the same but i don't know where i am making mistakes as firstly i have tried this code that i have seen from tutorial http://magenticians.com/magento-2-override-block/ and then i have implemented your code but still i am doing something wrong. Can you please guide me where i am making mistakes. 

 

 

module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magenticians_Modulecontact" setup_version="1.0.1">
</module>
</config>

registration.php 

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Magenticians_Modulecontact',
__DIR__
);

di.xml file

<?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\Contact\Block\ContactForm" type="Magenticians\Modulecontact\Block\ContactForm" />
</config>

 

Re: Overriding a block in Magento 2

Hi,

You are not posted contactForm.php code. You are fallowed the correct steps, If you want to know your module code is worked or not you need to fallow below points.

 

1) Add ContactForm.php file from Block folder and add below code

 

<?php

namespace Magenticians\Modulecontact\Block;

class ContactForm extends \Magento\Contact\Block\ContactForm{

    /**
     * Returns action url for contact form
     *
     * @return string
     */
    public function getFormAction()
    {
        return $this->getUrl('contact/index/newAction', ['_secure' => true]);
    }

}

2) fallow the below commands.

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy

3) Navigate your browser to http://localmagento2.com/contact.

 

If you observe the url of your contact form tag your newAction will added like below.

 

http://localmagento2.com/contact/index/newAction/

If you have any queries send it .zip format of your module to bojjaiah.t@gmail.com, I will look on to that.

Have a great day.