In this post I am going to explain how to remove block from layout on specific condition Magento 2.
If you have a specific condition to add/remove block then you can achieve it by observer.
Here I have given the example to remove search block.
First you need to create event.xml file on below path.
Path: app/code/<vendor>/<module>/etc/frontend/events.xml
<?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="remove_search_block" instance="<vendor>\<module>\Observer\RemoveBlockSearch" />
</event>
</config>Now, create observer on below path.
Path: app/code/<vendor>/<module>/Observer/RemoveBlockSearch.php
<?php
namespace <vendor>\<module>\Observer;
use Magento\Framework\Event\Observer;
class RemoveBlockSearch implements \Magento\Framework\Event\ObserverInterface
{
public function execute(Observer $observer)
{
$layout = $observer->getLayout();
$block = $layout->getBlock('top.search');
if ($block) {
// Here you can add yout condition
$layout->unsetElement('top.search');
}
}
}After adding above code, search block will removed from the Header.
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!



Leave a Reply