Hello Magento Friends,
In today’s blog, I am going to show How to Remove a Block from Any Page using Observer in Magento 2.
Blocks are used to display pieces of content placed anywhere on the page. Blocks contain text, image or video. Blocks can be added and removed anytime when required. Usually while adding or removing blocks, you need to modify the layout XML file. But sometimes users need to remove the block without modifying the layout file.
Let’s learn How to Remove Block using Observer in Magento 2.
Step 1: We need to create an “events.xml” file inside our extension at the following path
app\code\Vendor\Extension\etc\
Then add the code as follows
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <event name="layout_generate_blocks_after"> <observer name="removeblock" instance="Vendor\Extension\Observer\Removeblock" shared="false" /> </event> </config>
Step 2: After that, we need to create a “Removeblock.php” file inside our extension at the following path.
app\code\Vendor\Extension\Observer\
Now, append the below code
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; class Removeblock implements \Magento\Framework\Event\ObserverInterface { public function execute(\Magento\Framework\Event\Observer $observer) { $layout = $observer->getLayout(); $your_condition = 1; // write your conditional logic here if($your_condition == 1) { // you need to modifed block name as per your requirement. $layout->unsetElement('customer-account-navigation-orders-link'); } } }
This way you can easily Remove Block from Any Page using Observer in Magento 2. Also checkout, How to Remove Blocks From Layout Magento 2.
If you have any doubt regarding the above-mentioned steps, connect with me through the comment section. Share the article with your Magento colleagues and stay in touch with us
Happy Reading!
Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…
In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…
October was an exciting month for MageComp! From significant updates across our Magento 2 extension…
In modern web development, seamless navigation and state management are crucial for delivering a smooth…
Magento Open Source 2.4.8 beta version released on October 8, 2024. The latest release of…
Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…