How to Remove Block Depending on a Config Setting?

Remove Block Depending on a Config Setting

In this topic we will show you How to Remove Block Depending on a Config Setting through 2 steps:

  • Step 1: Create your events.xml
  • Step 2: Create RemoveBlock.php

Step 1: Create your events.xml

Create your events.xml in events.xml file in app\code\[Name_Space]\Your_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="[Name_Space]\[Your_Module]\Model\Observer\RemoveBlock" />

</event>

</config>

Step 2: Create RemoveBlock.php

Create RemoveBlock.php in app\code\[Name_Space]\[Your_Module]\Model\Observer

<?php

namespace [Name_Space]\[Your_Module]\Model\Observer;

use Magento\Framework\Event\Observer;

use Magento\Framework\Event\ObserverInterface;

class RemoveBlock implements ObserverInterface

{

protected $_scopeConfig;

public function __construct(

    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig

) {

    $this->_scopeConfig = $scopeConfig;

}

public function execute(Observer $observer)

{

    /** @var \Magento\Framework\View\Layout $layout */

    $layout = $observer->getLayout();

    $block = $layout->getBlock('dashboard');

    if ($block) {

        $remove = $this->_scopeConfig->getValue(
            'dashboard/settings/remove',

            \Magento\Store\Model\ScopeInterface::SCOPE_STORE

        );

        if ($remove) {

            $layout->unsetElement('dashboard');

        }

    }

}

}

The steps mentioned above are the shortest process \to Remove Block Depending on a Config Setting. With this guide, you can manage the Config Setting in Magento 2 easily. Every store has a Config Setting in Magento 2 with many attributes.

For more Magento KB, visit Webnexs Knowledge Base.

 

Last Update: October 4, 2018  

October 4, 2018   122   Praveen Raja    Magento 2 Tutorial    
Total 0 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

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

Facebook
Twitter
INSTAGRAM
LinkedIn