If you are using Magento 2 and wish to remove a block from the layout without any restrictions, see this blog post:
Now, if you have a precise requirement to display the block or not, observer can help you with that.
After all blocks are prepared for rendering on the web page, the ‘layout_generate_blocks_after’ event is dispatched. This event can be used to change the blocks on the current page or the blocks for the page you want to change.
As we can see, “layout_generate_blocks_after” is sent out after the layout creates all of the elements and contains the “full_action_name” and “layout,” which we can access directly in the observer.
For this first add the above event to events.xml
app/code/Vendor/Module/etc/area/events.xml
Where area can be :
- frontend
- adminhtml
- global (for this add events.xml directly under etc folder)
I am creating this on frontend area.
So the path will be: app\code\Vendor\Module\etc\frontend\events.xml
Code Content:
1 2 3 4 5 6 |
<?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="vendor_module_observer_frontend_layout_generateblocksafter_layout_generate_blocks_after" instance="Vendor\Module\Observer\Frontend\Layout\GenerateOrRemoveBlocksAfter"/> </event> </config> |
Now, create observer file:
app\code\Vendor\Module\Observer\Frontend\Layout\GenerateOrRemoveBlocksAfter.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace Vendor\Module\Observer\Frontend\Layout; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\View\Layout; /** * Class GenerateOrRemoveBlocksAfter add, remove or update blocks */ class GenerateOrRemoveBlocksAfter implements ObserverInterface { public function execute(Observer $observer) { /** @var \Magento\Framework\View\Layout $layout */ $layout = $observer->getLayout(); $block = $layout->getBlock('sales.order.info'); if ($block) { //you can apply or add your condition here. $layout->unsetElement('sales.order.info'); } } } |
Once you’ve added the necessary code to your module, the sales order details block will no longer appear on any pages, including the sales/order/view page in the My Account area.
bluethinkinc_blog
2023-08-08