How to Remove Block from Any Page using Observer in Magento 2

How to Remove Block from Any Page using Observer in Magento 2

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.

Steps to Remove Block from Any Page 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');
        }
    }
}

Conclusion:

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!

Previous Article

How To Show Prefix Field In Magento 2

Next Article

How to Configure Quick Order in Magento 2

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨