How to remove blocks programmatically in Magento 2?

How to remove blocks programmatically in magento 2?

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

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

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 Reply

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