Magento E-commerce Platform Q/ A

How to Add Custom Renderer to Magento Grid

Magento Grid – a very handy tool for flexible data display. In Magento it is usually  presented as a table. There is a possibility to modify tables if necessary.

To do this, you need to add a column to Magento grid and overwrite the default renderer with a custom one.

In the example below, instead of product id we will be displaying product image in 'Product' id column.  You can see default meaning of the column (before customization):

235

Use this code to add a custom renderer:

<?php

class Ikantam_BasicLoyalty_Block_Adminhtml_User_Grid extends Mage_Adminhtml_Block_Widget_Grid
{       
… 
$this->addColumn('product', array(
'header' => $this->__('Product'),
            'align'  => 'center',
            'index'  => 'product_id',
            'width'  => '50px',
            'renderer'  => 'Ikantam_BasicLoyalty_Block_Product'
));
…		
	
}

 

Now we will create the block indicated in the parameter renderer of the modified column. We will use this code (code of the block: Ikantam_BasicLoyalty_Block_Product):

<?php

class Ikantam_BasicLoyalty_Block_Product extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{	

public function render(Varien_Object $row)
{
$productId =  $row->getData($this->getColumn()->getIndex());
$product = Mage::getModel('catalog/product')->load($productId);

$value = '<img src="">';
if($product->getImage()!= 'noselection')
{
     $value='<img src="' . $product->getImageUrl() . '" width="100" height="100" />';
}

return $value;
}
}

 

That's it, as you can see on the image below, now instead of the product id in 'Product' column the image of the product is displayed.

236