How to eliminate block depending on a config setting in Magento 2?

Learn how to eliminate block depending on a config setting in Magento 2 here in this blog.

By using two steps we will be able to remove block depending on a config setting in Magento 2. The following steps are:

Step 1: create your Event.xml

Step 2: create a removed block. PHP

Get reliable business partner that helps your online store sell more with Webnexs!!!

How to eliminate block IN Magento 2?

Create your Event.xml

Construct your event.xml in the Event.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>

Create a remove block.php

Construct your remove block.php by

 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 above-mentioned steps are the shortest process to eliminate block in Magento depending on a config setting. The following steps can manage the config setting in Magento 2 effortlessly.

eliminate block in magento


Posted

in

, ,

by

Comments

2 responses to “How to eliminate block depending on a config setting in Magento 2?”

  1. Alex Joshi Avatar
    Alex Joshi

    I would read more tutorials about removing block depending on a configuration setting in Magento 2. But this is the first tutorial that explains it in a simple and easy way.- Thanks

  2. Mage ruddy Avatar
    Mage ruddy

    Thanks for sharing this great tutorial,that was of great help to start with.

Leave a Reply

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