Override a Block in Magento 2

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.


Let’s begin:
1. Create file: /app/code/MagentoSharing/Example/etc/di.xml

2. Set preference in di.xml file

using content:

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:

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

override a block in magento 2

After
override a block in magento 2
You can download the package of this tutorial here.

If you have any problem, leave a comment or contact us.

Leave a Reply

Your email address will not be published.