Magento Admin Grid provides the tabular data from database in grid format. This is convenient for all text data. In Some cases we may have other data type to be shown in grid which is not plain text data. For example Image data.
For this purpose magento provides us the flexibility to define our own column renderer. We can use this to add additional markup before and after the required data.
In this article we will see how to add our own column renderer to show an image file in our custom module. I’ll cover only the portions that show the image in admin grid. After adding our basic skeleton module. we need to do a few additional steps.
Step 1: In this step we are adding and saving some test data. Initially our grid will display only the image name.
Step 2: Our Admin Grid coding initally looks as show below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php class Mydons_Imagegrid_Block_Adminhtml_Imagegrid_Grid extends Mage_Adminhtml_Block_Widget_Grid { //other method codings protected function _prepareColumns() { //other columns data $this->addColumn('filename', array( 'header' => Mage::helper('imagegrid')->__('Image Demo'), 'align' => 'center', 'index' => 'filename', )); } //remaining method coding } |
Lets assume that our image data is named filename.
Step 3: Now we need to create a block class that takes care of rendering the image data. Our custom renderer class should override the render method in the base class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
The block class will add the required markup and returns the image path as shown below. We assume that the image is uploaded in the media directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php class Mydons_Imagegrid_Block_Adminhtml_Imagegrid_Grid_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { public function render(Varien_Object $row) { if($row->getFilename()!='') return "<img src=". Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA). $row->getFilename() . " width=75 height = 60/>"; else return ''; } } |
Step 4: Rewrite the code of admin grid to include the custom renderer as shown
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php class Mydons_Imagegrid_Block_Adminhtml_Imagegrid_Grid extends Mage_Adminhtml_Block_Widget_Grid { //other method codings protected function _prepareColumns() { //other columns data $this->addColumn('filename', array( 'header' => Mage::helper('imagegrid')->__('Image Demo'), 'align' => 'center', 'index' => 'filename', 'type' => 'image', 'renderer' => 'imagegrid/adminhtml_imagegrid_grid_renderer_image', 'width' => '100px' )); } //remaining method coding } |
Step 5: After clearing the cache and refreshing the page the grid looks as shown below.
Compatability: Magento 1.7.0.0