:::: MENU ::::

Magento Certification: Rendering Blocks (part 4)

Magento Certification: Rendering Blocks (part 4)
9 votos, 4.22 media (84% puntos)

Describe events fired in blocks

How can block output be caught using an observer?

During the render phase, Magento calls the method toHtml for each block that is needed in the page being generated.

If you take a look at the Mage_Core_Block_Abstract::toHtml method, you’ll see that Magento fire a couple of events, one at the beginning and the other at the end of the method.

final public function toHtml() {

    Mage::dispatchEvent('core_block_abstract_to_html_before', array('block' => $this));
    . . .
    Mage::dispatchEvent('core_block_abstract_to_html_after', array('block' => $this, 'transport' => self::$_transportObject));

    $html = self::$_transportObject->getHtml();
    return $html;

First event (core_block_abstract_to_html_before) can be captured to modify the behaviour of the block, setting some variables that are used by the template, or adding/removing childs and so on.

The second one (core_block_abstract_to_html_after) is the one that allow us to catch the output and modify it. We’ll need a custom module for doing this, and then, we can add an observer in the module config.xml file with the following lines:


In our Magento module, we’ll need to define an Observer Model, and a public method myObserverMethod, which should look like the following:

public function myObserverMethod($observer) {

    $block = $observer->getBlock();
    $transport = $observer->getTransport();
    if ($block->getNameInLayout() == 'top.links') {
        $transport->setHtml('show this content instead');

In this example, this method will check for top.links block generation, and it will change its output content by the single line ‘show this content instead’.

You must use this with care, as this method will be called by Magento for each single block generated in the Magento rendering process (may be docens of blocks). Keep this method as simple as possible or the performance may drop dramatically.

What events do Mage_Core_Block_Abstract and Mage_Core_Block_Template fire?

Events fired by Mage_Core_Block_Abstract are the previously commented, and the next two:

 core_block_abstract_prepare_layout_before core_block_abstract_prepare_layout_after

These events are fired by Magento system during the block creation from the main Layout class instance and are out of the scope of this question.

Mage_Core_Block_Template does not fire any additional event apart from the four already commented. As Mage_Core_Block_Template inherits from Mage_Core_Block_Abstract, the four events apply as well.

Hey! Qué opinas sobre el artículo?