Programmatically: How to create custom Magento admin grids
Step 1: Create a new module with etc/module.xml file
Create a new directory MyCompany/MyModule and add the following etc/module.xml file:
<?xml version="1.0"?>
<config>
<modules>
<MyCompany_MyModule>
<version>1.0.0</version>
</MyCompany_MyModule>
</modules>
</config>
Step 2: Define the grid in etc/adminhtml/grid.xml file
Create a new directory app/code/local/MyCompany/MyModule/etc/adminhtml and add the following grid.xml file:
<?xml version="1.0"?>
<config>
<adminhtml>
<grid>
<my_custom_grid translate="label">
<label>My Custom Grid</label>
<classes>
<name>MyCompany_MyModule::grid/my_custom_grid</name>
</classes>
</my_custom_grid>
</grid>
</adminhtml>
</config>
Step 3: Create a new PHP class that extends Mage_Adminhtml_Block_Widget_Grid and overrides the prepareCollection() and addMassaction() methods
Create a new directory app/code/local/MyCompany/MyModule/Block/Adminhtml and add the following PHP class:
class MyCompany_MyModule_Block_Adminhtml_Grid_MyCustomGrid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('my_custom_grid');
$this->setDefaultSort('id');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(true);
}
protected function _prepareCollection()
{
$collection = Mage::getModel('mycompany_mymodule/my_model')->getCollection();
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _addMassaction()
{
if (!Mage::app()->isSingleStoreMode()) {
$this->getMassactionBlock()->addItem('delete', array(
'label' => Mage::helper('adminhtml')->__('Delete'),
'url' => $this->getUrl('*/*/massDelete'),
'confirm' => array(
'title' => Mage::helper('adminhtml')->__('Delete Items'),
'message' => Mage::helper('adminhtml')->__('Are you sure you want to delete these items?')
)
));
}
return parent::_addMassaction();
}
}
Step 4: Register the grid in etc/adminhtml/routes.xml file
Create a new directory app/code/local/MyCompany/MyModule/etc/adminhtml and add the following routes.xml file:
<?xml version="1.0"?>
<config>
<adminhtml>
<acl>
<resources>
<admin> <!-- You need to have this resource defined -->
<children>Mymodule</children>
</admin>
</resources>
</acl>
<routers>
<adminhtml>
<uses> <!-- Use the default admin router -->
<default/>
<mymodule> <!-- Define our custom router -->
<module>MyCompany_MyModule</module>
<frontName>mymodule</frontName>
</mymodule>
</uses>
</adminhtml>
</routers>
</adminhtml>
</config>