Rewriting Blocks in Magento

The last few days i have been toying with Magento. and mainly trying to wrap my head around the file structure. It takes quite some time to find all files. So i will be making notes here to keep track of my own progress :)

Today i wanted to add a tab in the customer section of the admin. I am working on a new module and this should be configurable on a per user basis. There for i needed an extra tab to the customer > Manage customers > [customer x] page.

The first challenge was to figure out where Magento stores the tab menu data. I was hoping this came from a database. But after some searching i couldn’t find any reference. It seems to be hard coded in tab files. The customer tab in question can be found here:

app/code/core/Mage/Adminhtml/Block/Customer/Edit/tabs.php

We could of course edit this class. But that’s not according the Magento way. We need to create a local copy of this class. preferably under my own namespace.

To make this happen we first need to tell Magento we are rewriting core modules. So we start of by creating the following file

app/etc/modules/[namespace]_All.xml

And we add the following lines

<config>
  <modules>
    <strawberries_core>
      <active>true</active>
      <codepool>local</codepool>
      <depends>
        <mage_core></mage_core>
          </depends>
      </strawberries_core>
  </modules>
</config>

This will tell Magento we have a Core folder under our own namespace. But it still depends on the Mage_Core classes if they are not available in the namespaced location.

Next we need to setup the [namespace]_Core module. We create the folder structure under our own namspace

app/code/local/[namespace]/Core/etc

And we create a new config file here (config.xml) where we will do the actual class rewriting.

<config>
  <modules>
    <[namespace]_Core>
    <version>0.1.0</version>
  </modules>
<global>
  <blocks>
    <adminhtml>
      <rewrite>
        <customer_edit_tabs>[namespace]_Adminhtml_Block_Customer_Edit_Tabs</customer_edit_tabs>
      </rewrite>
    </adminhtml>
  </blocks>
</global>
</config>

We use the tag to tell Magento we are rewriting a Block class. And then we setup the actual rewrite.

Mage_Adminhtml_Block_Customer_Edit_Tabs is now rewritten too [namespace]_Adminhtml_Block_Customer_Edit_Tabs

The only thing left now is to create the Block class which is located in

app/code/local/[namespace]/Adminhtml/Block/Customer/Edit/Tabs.php

class [namespace]_Adminhtml_Block_Customer_Edit_Tabs extends Mage_Adminhtml_Block_Customer_Edit_Tabs
{
  protected function _beforeToHtml()
  {
    $this->addTab('modulename', array(
      'label'     => Mage::helper('customer')->__('Modulename'),
      'class'     => 'ajax',
      'url'       => $this->getUrl('*/*/modulename', array('_current' => true)),
    ));
    
    $this->_updateActiveTab();
    return parent::_beforeToHtml();
  }
}
comments powered by Disqus