Magento: Add custom column in admin grid with own data & filter

29. August 2014 at 13:18

How to create a custom grid filter with a new column with own data (not from collection) and filter this data?

First Step

Enhance the grid, for example extends the Mage_Adminhtml_Block_Catalog_Category_Tab_Product

overwrite the  _prepareColumns() methode with new column

      $this->addColumn('price_yesno', array(
            'header'    => Mage::helper('catalog')->__('Price exist'),
            'sortable'  => true,
            'width'     => '60',
            'index'     => 'price',
            'type'      => 'options',
            'align'     => 'center',
            'renderer'  => 'Fly2mars_Catalog_Block_Adminhtml_Category_Renderer_Hasprice',
            'editable'  => 0,
            'options' => array('1' => 'Yes', '0' => 'No'),
            'filter_condition_callback' => array($this, '_filterHasPrice')
        ));
return Mage_Adminhtml_Block_Widget_Grid::_prepareColumns();

And add in the same class the following callback methode

    protected function _filterHasPrice($collection, $column)
    {
        $value = $column->getFilter()->getValue();
        $collection = $this->getCollection();
        if($value == 1) {
            $collection->addFieldToFilter('price', array('notnull' => true));
        } else {
            $collection->addFieldToFilter('price', array('null' => true));
        }
        return $this;
    }

Second Step

You need the renderer, for this example you add in the file Fly2mars_Catalog_Block_Adminhtml_Category_Renderer_Hasprice

class Fly2mars_Catalog_Block_Adminhtml_Category_Renderer_Hasprice
    extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    /**
     * Check if product has price
     *
     * @param   Varien_Object
     * @return  string
     */
    protected function _getValue(Varien_Object $row)
    {
        if($row->getData('price') != '') {
            return 'Yes';
        }
        return 'No';
    }
}

that’s it.

Please share this article von facebook & google plus or where you want, thank you!

Daniel Briegert

Daniel Briegert

xing: https://www.xing.com/profile/Daniel_Briegert

More Posts - Website

Follow Me:
TwitterFacebook