Programmatically: How to create custom Magento product grids
Step 1: Create a new PHP file
Create a new file in the app/code/local/[YourCompany]/[YourModule]/Block directory, e.g., MyGrid.php. In this example, I'll use MyGrid as the filename.
Step 2: Define the grid class
In MyGrid.php, define the class that extends Mage_Adminhtml_Block_Widget_Grid:
class MyCompany_MyModule_Block_Adminhtml_Mygrid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('mygrid');
$this->setDefaultSort('name');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(true);
}
}
Step 3: Define the grid columns
Add a method to define the grid columns:
public function getColumns()
{
return array(
'name' => array(
'header' => Mage::helper('mymodule')->__('Product Name'),
'index' => 'name',
'type' => 'text',
),
'price' => array(
'header' => Mage::helper('mymodule')->__('Price'),
'index' => 'price',
'type' => 'price',
),
);
}
Step 4: Define the grid collection
Add a method to define the grid collection:
public function getCollection()
{
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect(array('name', 'price'));
return $collection;
}
Step 5: Include the grid in your module
Add a method to include your custom grid in your module's configuration file (config.xml):
MyCompany_MyModule_Block
And in your module's layout XML file (layout.xml):
Step 6: Create a grid template
Create a new file in the app/design/adminhtml/default/template/ mycompany/mymodule/ directory, e.g., grid.phtml. This is where you'll render your grid:
echo $this->getGridHtml();