Change Layout Before Load in Magento 2

Today we will learn how to Change layout before page Loads. We know that magento has many Defined events like layout_load_before,_load_afterand many more.

Lets take one event and try to understand.

layout_load_before this event means change layout before the pages load. So we will change our layout on configuraion base.

create etc/event.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="layout_load_before_abc" instance="PME\SuccessPage\Observer\AddHandel" />
    </event>
</config>

in above code we have mentioned out event name that is  layout_load_before, change this according to your desire event name.
we need an observer class to check the event, so created an observer for that event.

Now lets create an Observer/AddHandel.php

<?php

namespace PME\SuccessPage\Observer;
   
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\View\LayoutInterface;
use PME\SuccessPage\Helper\Data;

class AddHandel implements ObserverInterface
{
    private $helper;

    public function __construct(
        Data $helper
    ) {
        $this->helper = $helper;
    }

    public function execute(Observer $observer)
    {
      // echo $this->helper->moduleEnabled();exit;
            $layout = $observer->getEvent()->getLayout();
       if ($this->helper->moduleEnabled()) {
           $layout->getUpdate()->addHandle("successpage_onepage_successs"); //Name of layout_file_name.xml
       } else {
           $layout->getUpdate()->addHandle("checkout_onepage_success"); //Name of layout_file_name.xml
       }
    }
    
}

Thats it. 🙂 Happy Coading

About Ejaz Alam

A Software Engineer who Believes in a simple lifestyle and follow a simple logic to make himself better than yesterday. :)

View all posts by Ejaz Alam →

Leave a Reply

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