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 remove block .php
Create your Event.xml
Construct your event.xml in 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 remove a block depending on a config setting .The following steps can manage the config setting in Magento 2 effortlessly.
Last Update: July 17, 2018
February 6, 2018 804 Nandini Ramachandran Java Script
Total 1 Votes:
0
1
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
Thanks for sharing this great tutorial,that was of great help to start with.