Introduction
There are lots of events in Magento which are dispatched by default. Among them ‘core_block_abstract_to_html_after’ is the one.
Recently we have re-developed the Easy Template Path Hints extension using this event as the previous version of the extension has some confliction issues with other modules.
In this article we will demonstrate the implementation of ‘core_block_abstract_to_html_after’ event in Easy Template Path Hints Extension:
1. Register the ‘core_block_abstract_to_html_after’ event
app/code/local/MagePsycho/Easypathhints/etc/config.xml
...
<global>
...
<events>
<core_block_abstract_to_html_after>
<observers>
<easypathhints_core_block_abstract_to_html_after>
<class>easypathhints/observer</class>
<method>setTemplatePathHints</method>
</easypathhints_core_block_abstract_to_html_after>
</observers>
</core_block_abstract_to_html_after>
</events>
...
</global>
...
2. Implementing the Observer
<?php
/**
* @category MagePsycho
* @package MagePsycho_Easypathhints
* @author [email protected]
* @website https://www.magepsycho.com
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class MagePsycho_Easypathhints_Model_Observer {
public function setTemplatePathHints(Varien_Event_Observer $observer) {
/* @var $block Mage_Core_Block_Abstract */
$block = $observer->getBlock();
$transport = $observer->getTransport();
$fileName = $block->getTemplateFile();
$thisClass = get_class($block);
if($fileName){
$preHtml = '<div style="position:relative; border:1px dotted red; margin:6px 2px; padding:18px 2px 2px 2px; zoom:1;">
<div style="position:absolute; left:0; top:0; padding:2px 5px; background:red; color:white; font:normal 11px Arial;
text-align:left !important; z-index:998;" onmouseover="this.style.zIndex=\'999\'"
onmouseout="this.style.zIndex=\'998\'" title="'.$fileName.'">'.$fileName.'</div>';
$preHtml .= '<div style="position:absolute; right:0; top:0; padding:2px 5px; background:red; color:blue; font:normal 11px Arial;
text-align:left !important; z-index:998;" onmouseover="this.style.zIndex=\'999\'" onmouseout="this.style.zIndex=\'998\'"
title="'.$thisClass.'">'.$thisClass.'</div>';
$postHtml = '</div>';
}else{
$preHtml = null;
$postHtml = null;
}
$html = $transport->getHtml();
$html = $preHtml . $html . $postHtml;
$transport->setHtml($html);
}
}
Notes: From the above code, you can see that we can easily find the related $block object and $transport object which is very handy in order to find the block class, the template file, modify the block output ($transport->setHtml()), etc.
Isn’t that cool way to modify the core code without touching it?
FYI, Event-Observer technique is always the best method for modifying core code.
Don’t forget to provide the feedback/comments if there’s any.
Happy E-commerce!!