How To Remove Block Depending on Config Setting in Magento 2

I’ve earlier posted a solution to remove a block from the layout in Magento 2

But what if you want to remove block depending on config setting in Magento 2 store?

It may happen that based on certain conditions, you want to display a block or eliminate it.

For example, you want to disable the account registration based on a specific condition and hence remove the login block.

Implement the below method for similar scenarios and handle conditional behaviors like a pro! 

Method to Remove Block Depending on Config Setting in Magento 2:

1. Create events.xml file in app\code\[Vendor]\[Module]\etc

<?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_block" instance="[Vendor]\[Module]\Model\Observer\RemoveBlock" />
    </event>
</config>

2. Create RemoveBlock.php file in app\code\[Vendor]\[Module]\Model\Observer

<?php

namespace [Vendor]\[Module]\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class RemoveBlock implements ObserverInterface
{
    protected $_scopeConfig;

    public function __construct
    (
        ScopeConfigInterface $scopeConfig
    )
    {
        $this->_scopeConfig = $scopeConfig;
    }

    public function execute(Observer $observer)
    {
        /** @var \Magento\Framework\View\Layout $layout */
        $layout = $observer->getLayout();
        $block = $layout->getBlock('customer.new');  // here block reference name to remove

        if ($block) {
            $remove = $this->_scopeConfig->getValue('path_system_config', ScopeInterface::SCOPE_STORE);
            if ($remove) {
                $layout->unsetElement('customer.new');
            }
        }
    }
}

That’s it.

It was never this easy to eliminate block depending on config setting in Magento 2!

Feel free to share the solution via social media with the fellow developers

Thanks.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...