In this tutorial, we will see, how we can remove layout blocks using PHP programmatically instead of working in the layout.xml file in Magento 2.
I have already shown how to Remove Blocks or containers from Layout in Magento 2?, but in some cases, you will need to remove blocks using dynamic conditions.
In that case, we can check and remove the block using the use of event observers.
To achieve this, we can use the “layout_generate_blocks_after” event and create its observer to add our dynamic condition to remove the block.
In the below example, We will see how to remove specific blocks programmatically if the customer is not logged in using an event observer.
Step 1: Define the event in events.xml
file in your custom module.
app/code/Jigar/CustomModule/etc/frontend/events.xml
<?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_for_guests" instance="Jigar\CustomModule\Model\Observer\RemoveBlockForGuests" />
</event>
</config>
Here we have added an observer which will be called when the layout_generate_blocks_after is triggered, Now we can add our logic in the observer as below.
Step 2: Define Observer file RemoveBlockForGuests.php
app/code/Jigar/CustomModule/Observer/RemoveBlockForGuests
.php
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Jigar\CustomModule\Model\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Http\Context as HttpContext;
class RemoveBlockForGuests implements ObserverInterface
{
/**
* @var HttpContext
*/
protected $httpContext;
public function __construct(
HttpContext $httpContext
) {
$this->httpContext = $httpContext;
}
public function execute(Observer $observer)
{
/** @var \Magento\Framework\View\Layout $layout */
$layout = $observer->getLayout();
$isCustomerLoggedIn = (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
if (!$isCustomerLoggedIn) {
$blockName = 'your-block-name-to-remove';
$block = $layout->getBlock($blockName);
if ($block) {
$layout->unsetElement($blockName);
}
}
}
}
In the above example, we have checked and removed the block if the customer is not logged in. You can change and update the observer code as per your requirements.
You may also like :
How to Remove Blocks or Containers From Layout in Magento 2?
How to use ifconfig in layout xml Magento 2?
That’s it for this blog. Thank You 🙂
Leave a Comment