Add custom renderer for a custom column in Magento grid

Add custom renderer for a custom column in Magento grid

Every now or then we need new column on some grid listing in Magento. It is quite simple task, but you will probably want to format values way you want or whatever.
This is where writing your own renderer would be usefull and simple.

To pull this out, you would overide some grid,  add column  to it and write custom renderer.

How it works in real life situations.?!
Let’s take a look at product listing admin grid.
Overide block class called Mage_Adminhtml_Block_Catalog_Product_Grid located in /app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php file.

We won’t rewrite this block in this post, but this post assumes you know how to do it yourself.
Modify _prepareCollection() method with new data, for example let’s add short description of a product:

protected function _prepareCollection()
{
$store = $this->_getStore();
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('sku')
->addAttributeToSelect('name')
->addAttributeToSelect('short_description') // THIS IS WHAT WE HAVE ADDED
->addAttributeToSelect('attribute_set_id')
->addAttributeToSelect('type_id')
->joinField('qty',
'cataloginventory/stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left');
 
if ($store->getId()) {
//$collection->setStoreId($store->getId());
$collection->addStoreFilter($store);
$collection->joinAttribute('custom_name', 'catalog_product/name', 'entity_id', null, 'inner', $store->getId());
$collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner', $store->getId());
$collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner', $store->getId());
$collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $store->getId());
}
else {
$collection->addAttributeToSelect('price');
$collection->addAttributeToSelect('status');
$collection->addAttributeToSelect('visibility');
}
 
$this->setCollection($collection);
 
parent::_prepareCollection();
$this->getCollection()->addWebsiteNamesToResult();
return $this;
}

Now let’s add this to a new column:

/*You will find some more code inside this method, but for readability purposes, I'll just say you need to add code you find here at beginning of this method...*/
 
protected function _prepareColumns()
{
$this->addColumn('Short description',
array(
'header'=> Mage::helper('catalog')->__('Short description'),
'index' => 'short_description',
'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Red',// THIS IS WHAT THIS POST IS ALL ABOUT
));
 
}

Make directory called Renderer inside directory where your Grid.php is located and make file Red.php

Make class

Mage_Adminhtml_Block_Catalog_Product_Renderer_Red extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract

Notice “Mage_”, this is because I’m not rewriting anything in this post…

Here is code:

< ?php class Mage_Adminhtml_Block_Catalog_Product_Renderer_Red extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { public function render(Varien_Object $row) { $value =  $row->getData($this->getColumn()->getIndex());
return '<span style="color: red;">'.$value.'</span>';
 
}
 
}
?>

Now you should have one additional column at product grid containing short description writen in red.

If you feel like you would need a team of experts to help you out with this, or any other Magento development related subject, we would be happy to assist you. Our Magento Technical Audit is a great place to start improving your store.

Related Inchoo Services

You made it all the way down here so you must have enjoyed this post! You may also like:

How To Connect Google Analytics 4 To Magento 2 Bojan Mareljic
Bojan Mareljic, | 36

How To Connect Google Analytics 4 To Magento 2

3 best open-source eCommerce platforms in 2021 Zrinka Antolovic
Zrinka Antolovic, | 8

3 best open-source eCommerce platforms in 2021

Show product thumbnail in grids Petar Sambolek
Petar Sambolek, | 14

Show product thumbnail in grids

26 comments

  1. Hi Thomas,

    Can you please let me know , how to add a view link in the check box column on the order grid page.

  2. Great Post!

    I have a question, When a created a grid in admin but the info is not from the database, it’s from a web service, the default option like sort, filter and search doesn´t work. Do yo know how to make a “Custom grid” but with the correctly funcionallity??. Thanks in advance

  3. Hello, I need to add plain_value to Custom Variables Grid (All stores view), I added

    $this->addColumn('plain_value', array(
                'header'    => Mage::helper('adminhtml')->__('Value'),
                'index'     => 'plain_value',
            ));

    to …./system/variable/grid.php

    But no value, what I miss?
    Thanks all!!

  4. how to get link of custom module in magento and show link in dashboard in magento admin

  5. Hi, I added a new column to my product grid (this column is not an product attribute, so i made a join on the product collection), a selectable dropdown.Everithing is ok but my problem is that i can’t manage to send the selected value trough post to the other pages, so when i changed and go to a different page and return, the value is changed back to it’s default. How should i send this value to other pages like when clicking on the checkbox?

  6. I want to add new custom field backend when create new customer from create new order from sales in Order from magento backend.

    Is it possible or how ?

  7. Hi, It Is nice but i am facing problem.when i filter data or search in admin grid.
    searching and sorting not working ?

  8. Hi,

    AFAIK, filtering doesn’t work for renderer column. If you want the column to be filterable then use normal column instead.

    Thanks
    MagePsycho

  9. Greeting there,

    Very useful code and working fine but when go for filter then renderer column is disappear from the product grid means filter is not working on renderer column.

    Please post the soution for this problem.

    Thanks,
    Jignesh

  10. HI Tomas. its nice post. It helped me.
    I re-wrote the sales order grid. I wanted the customer’s email in grid too. for that I wrote the renderer as
    [code]&lt;?php

    class Mage_Adminhtml_Block_Renderer_Customer extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
    {

    public function render(Varien_Object $row)
    {
    $model = Mage::getModel(‘customer/customer’)-&gt;load($row-&gt;getCustomerId());

    return $model-&gt;getEmail();

    }

    }
    [/code]

    & in my rewritten grid I added the col as

    [code][/code][/code]
    $this->addColumn(‘customer_email’, array(
    ‘header’ => Mage::helper(‘sales’)->__(‘Customer Email’),
    ‘renderer’ => ‘adminhtml/renderer_customer’,

    ));
    [/cdoe]

    I am having the email as desired. But these col is having a lot of trailing & leading spaces, dhue to which I think its not searchable
    Can you suggest anything to remove those whitespaces? Thanks

    Regards

  11. Hi, thanks for the tutorial, i was wondering if anyone knows how to show if a product has an image?
    the code below shows 0 for items with an image and nothing if they don’t have an image which is fine i guess.. but i’d like to make it display yes/no can anyone help?!

    ->addAttributeToSelect(‘image’)

    $this->addColumn(‘image’,
    array(
    ‘header’=> Mage::helper(‘catalog’)->__(‘Has Image’),
    ‘width’ => ‘100px’,
    ‘type’ => ‘number’,
    ‘index’ => ‘image’,
    ));

  12. hm… It works when I hack the core. When I try to implement on my module, it throws ‘Mage_Core_Exception’ with message ‘Invalid block type:’ exception.

  13. Hi all,

    wondering someone could help.

    heres what ive done so far

    1. Ive created a new column in the orders grid in admin

    2. ive created a new table called:

    add_info

    which has the following fields:

    addinfo_id
    entity_id (this is populated with the order entity id)
    value (this is the value i want to display in the new column)

    Im having trouble population the new column : (

    please can someone guide me to how i can populate the new column with the data in the “value” field

    thanks you soo much!!

  14. @loopion Thanks for feedback. I’ll try your code as soon as I get to similar task, seems nice and short 🙂

  15. I’ve just did the same on a project for displaying images from one of our custom extension.

    Another solution:

    You can extend the Column.php from app/code/local/Adminhtml/Block/Widget/Grid by adding to _getRendererByType() your new renderer.

        protected function _getRendererByType()
        {
            switch (strtolower($this->getType())) {
                case 'image':
                    $rendererClass = 'adminhtml/widget_grid_column_renderer_image';
                    break;
                default:
                    $rendererClass = parent::_getRendererByType();
                    break;
            }
            return $rendererClass;
        }

    And then create your custom renderer (mine Image.php) into the app/code/local/Adminhtml/Block/Widget/Grid/Column/Renderer like you explained. (you should maybe add a function to get the full URL of your image if it comes from the products for example)
    You can even create your custom filter app/code/local/Adminhtml/Block/Widget/Grid/Column/Filter in my case Image.php

    Next, on your Grid.php instead of

    'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Red',

    write

    'type'  => 'image',

    Very good article and extremely useful!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.