Magento 1.9 Module Layout – Add Block Dynamically in Event Observer

event-observerlayoutmagento-1.9module

I want to know how to use layout.xml with event observer.

I want to show a message in footer when payment made successfully.

I know I have to use the event checkout_onepage_controller_success_action

How to use controller or layout.xml with event observer?

Best Answer

The event checkout_onepage_controller_success_action is triggered right before the layout is rendered, so you can still manipulate it.

The observer only receives the order id as a parameter, so you have to get the layout via app model:

$layout = Mage::app()->getLayout();

Now you can do your changes programmatically, like this:

$messageBlock = $layout->createBlock('core/template', 'payment_message_block');
$messageBlock->setTemplate('payment_message.phtml');
$layout->getBlock('footer')->append($messageBlock);

If you use the controller_action_layout_load_before event, you can also load a custom layout handle like this, if on the success page:

if ($observer->getAction()->getFullActionName() === 'checkout_onepage_success') {
    $layout = $observer->getLayout();
    $layout->getUpdate()->addHandle('custom_layout_handle');
}

which you can define in XML:

<layout>
  <custom_layout_handle>
     <reference name="footer">
       <block type="core/template" name="payment_message_block" template="payment_message.phtml" />
     </reference>
  </custom_layout_handle>
</layout>

Update: The footer block is cached, so we have to make sure that a different version is fetched from the cache if the message is present. For example:

$footer = $layout->getBlock('footer');
$footer->setCacheKey(sha1($footer->getCacheKey() . '-payment-message');

how to pass genrated data to phtml file? which i am showing

Reference your block by name and use setData(). For example:

$block = $layout->getBlock('payment_message_block')->setData('messsage', 'Hello');

And in the template:

echo $this->getData('message');