Show Image in Magento admin grid

Posted on Updated on

Create a Image renderer in Magento admin Grid.
Scenario:
We have an entity which has a field and it stores the name of the image associated with the entity. Now we would like to show the image in the entity listing Grid instead of just the image name.
Lets consider the images associated with the entity is stored in a folder called xyz inside the magento media folder and the field contains the name of the image only. eg(pic1.jpg)

unrendered image
Here is the magento code for the solution to this task.

In your grid.php file add a new column. If field name is image, put the following code
$this->addColumn(‘image‘, array(
‘header’ => Mage::helper(‘module_name’)->__(‘Image’),
‘index’ => ‘image‘,
 ‘renderer’ => ‘Companyname_Modulename_Block_Adminhtml_Renderer_Image‘,
));
Note the renderer attribute, the value of the renderer attribute is the name of the class which we are going to create to render the display of this field.
Now create the renderer class
Companyname_Modulename_Block_Adminhtml_Renderer_Image
at app/code/[codepool]/[company_name]/[module_name]/[Block]/Adminhtml/Renderer/Image.php

that extends magento abstract column renderer class which is Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
and write the necessary code in the render function as shown below.
In our case we want to display the image from the image name provided. The name of the image can be found in the $row object as $row->getData($this->getColumn()->getIndex()). Now we can easily manipulate the output. In our case we will wrap the imagename in the html <img> tag and achieve our objective.
Class Companyname_Modulename_Block_Adminhtml_Renderer_Image extends
Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$value = $row->getData($this->getColumn()->getIndex());
return ‘<img src=”‘.Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).’xyz/’.$value.'” />’;
}
}

rendered image
Voila, the image names are replaced by the actual images.
Hope this was helpful to you.
Cheers!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s