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:
- Create events.xml file in app\code\[Vendor]\[Module]\etc
123456<?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> - Create RemoveBlock.php file in app\code\[Vendor]\[Module]\Model\Observer
1234567891011121314151617181920212223242526272829303132333435<?phpnamespace [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 removeif ($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!
However, if you still have doubts about the implementation, please mention them in the Comments section below and I’d be happy to help.
Feel free to share the solution via social media with the fellow developers 🙂
Thanks.
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 businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
Solved – PayPal Issue in Magento 2.3.3 Checkout
Solved – Magento PayPal Issue With Base Currency INR
Next