Override a Block in Magento 2 – In the last tutorial, you can learn how to create a table and model in Magento 2. Today I’ll tell you how to override a Block in Magento 2.
What we have to do:
– Build a Magento 2 extension structure. I’ll use the module in last tutorial, you can download it here.
– Set preference in di.xml file
– Define a class to override Magento core class.
Contents
Let’s begin:
1. Create file: /app/code/MagentoSharing/Example/etc/di.xml
2. Set preference in di.xml file
using content:
1 2 3 4 |
<?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="MagentoCustomerBlockFormRegister" type="MagentoSharingExampleBlockCustomerFormRegister" /> </config> |
Class MagentoCustomerBlockFormRegister will override class MagentoSharingExampleBlockCustomerFormRegister to edit register page title.
3. Create file: /app/code/MagentoSharing/Example/Block/Customer/Form/Register.php
with content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace MagentoSharingExampleBlockCustomerForm; use MagentoFrameworkViewElementTemplate; class Register extends MagentoCustomerBlockFormRegister { protected function _prepareLayout() { $this->pageConfig->getTitle()->set(__('Create Account')); return parent::_prepareLayout(); } protected function _toHtml() { $this->setModuleName($this->extractModuleName('MagentoCustomerBlockFormRegister')); return parent::_toHtml(); } } |
In this file, I define function _prepareLayout() just set new title for register page. You also can use a complex logic.
And the result:
Before
After
You can download the package of this tutorial here.
If you have any problem, leave a comment or contact us.