How to override block in Magento 2?

by filiberto , in category: PHP CMS , 9 months ago

How to override block in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 3 months ago

@filiberto 

In Magento 2, you can override a block by creating a new block class and extending the original block class. Here's an example of how you can do this:

  1. Create a new module and register it in app/code/[Vendor]/[Module]/registration.php:
1
2
3
4
5
6
<?php
MagentoFrameworkComponentComponentRegistrar::register(
    MagentoFrameworkComponentComponentRegistrar::MODULE,
    '[Vendor]_[Module]',
    __DIR__
);


  1. Create a di.xml file in app/code/[Vendor]/[Module]/etc to specify the original block class and the new block class:
1
2
3
4
5
<?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="MagentoCatalogBlockProductView" type="[Vendor][Module]BlockProductView"/>
</preference>
</config>


  1. Create the new block class in app/code/[Vendor]/[Module]/Block/Product/View.php:
1
2
3
4
5
6
7
8
<?php

namespace [Vendor][Module]BlockProduct;

class View extends MagentoCatalogBlockProductView
{
    // Your custom code goes here
}


  1. Run the following commands to enable the new module and clear the cache:
1
2
3
php bin/magento module:enable [Vendor]_[Module]
php bin/magento setup:upgrade
php bin/magento cache:clean


This will override the original block class with your new block class. You can then add custom functionality to the new block class by defining new methods or overriding existing methods.


Note: It is generally recommended to use plugins or preferences to extend or modify core functionality in Magento 2 instead of directly overriding classes. However, in some cases, overriding a block may be necessary.