Programmatically add a custom block in Magento Admin
Howdy! Recently I was in doubt about how to add custom Magento Block for my client’s requirements. One approach was to deal with it through .xml file, but when I was thinking about it I asked myself: “ Why add another .xml and load it?” And at this point, I decided to go with programmatic method.
Yeah, right! What is it all about? It is much easier to understand it than it may be to spell it. In this article we will cover complete section in deep and here you can download complete source code from my Github repository. We’ve got a lot of code to cover, so let’s get started!
Always, but always, my first point when I am developing custom module or examining existing one is config.xml ( of course this assumes that you set your “module registration file” under app/etc/modules/Inchoo_Adminblock.xml. ) After we set all of that we are going to create folder structure. And here we go with config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Inchoo_AdminBlock>
<version>1.0.0.0</version>
</Inchoo_AdminBlock>
</modules>
<global>
<blocks>
<inchoo_adminblock>
<class>Inchoo_AdminBlock_Block</class>
</inchoo_adminblock>
</blocks>
</global>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<inchoo_adminblock after="Mage_Adminhtml">Inchoo_Adminblock_Adminhtml</inchoo_adminblock>
</modules>
</args>
</adminhtml>
</routers>
</admin>
</config>
Here we define our block class which we can use for further development. Above that inside admin tags we defined our routers which will handle our URL and our route to the controller class. I use attribute “after” and that is where I am telling Magento: ” Hey partner! Can you load this to me after “Mage_Adminhtml“. With this approach Magento will always load its own controllers even in case that we called ours with the same name and put it in same structure, then it will call inchoo_adminblock.
Now we are going to do some magic and call that block programmatically. Go inside controller and type the following:
<?php
<?php
class Inchoo_Adminblock_Adminhtml_CreateController extends Mage_Adminhtml_Controller_Action{
public function indexAction(){
$this->loadLayout()
->_addContent(
$this->getLayout()
->createBlock('inchoo_adminblock/adminhtml_adminblock')
->setTemplate('inchoo/adminblock.phtml'))
->renderLayout();
}
}
Here we created our block which we defined in .config.xml and now we can put in it every logic or custom php method / parameters and call them in our template. Isn’t that nice and simple? We can easily test it with this URL: yourvirtualhost/admin/create/index/ and you can see that the job is done!