Magento custom filter on column in admin grid filter_condition_callback
Magento Grid Block has useful function for advanced filtering of a collection. It is called ‘filter_condition_callback’, and it is used in declaring a column. It takes actual collection, and callback function as parameters.
Major elements:
'filter_condition_callback' => array($this, 'filter_special_price'),
and:
public function filter_special_price($collection, $column) {
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$dateToday = Mage::app()->getLocale()->date()->toString('M/d/y');
$this->getCollection()->addAttributeToFilter('special_price', array('neq' => ''))
->addAttributeToFilter('special_from_date', array('date' => true, 'to' => $dateToday))
->addAttributeToFilter('special_to_date', array(
'or'=> array(
0 => array('date' => true, 'from' => $dateToday),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left');
return $this;
}
All Code:
getCategory()->getProductsReadonly()) {
$this->addColumn('in_category', array(
'header_css_class' => 'a-center',
'type' => 'checkbox',
'name' => 'in_category',
'values' => $this->_getSelectedProducts(),
'align' => 'center',
'index' => 'entity_id'
));
}
$this->addColumn('entity_id', array(
'header' => Mage::helper('catalog')->__('ID'),
'sortable' => true,
'width' => '60',
'index' => 'entity_id'
));
$this->addColumn('name', array(
'header' => Mage::helper('catalog')->__('Name'),
'index' => 'name'
));
$this->addColumn('sku', array(
'header' => Mage::helper('catalog')->__('SKU'),
'width' => '80',
'index' => 'sku'
));
$this->addColumn('price', array(
'header' => Mage::helper('catalog')->__('Price'),
'type' => 'currency',
'width' => '1',
'currency_code' => (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
'index' => 'price'
));
$this->addColumn('has_special_price', array(
'header' => Mage::helper('catalog')->__('Special price'),
'width' => '1',
'type' => 'checkbox',
'index' => 'Has special price',
'filter_condition_callback' => array($this, 'filter_special_price'),
));
$this->addColumn('position', array(
'header' => Mage::helper('catalog')->__('Position'),
'width' => '1',
'type' => 'number',
'index' => 'position',
'editable' => !$this->getCategory()->getProductsReadonly()
//'renderer' => 'adminhtml/widget_grid_column_renderer_input'
));
return parent::_prepareColumns();
}
public function filter_special_price($collection, $column) {
if (!$value = $column->getFilter()->getValue()) {
return $this;
}
$dateToday = Mage::app()->getLocale()->date()->toString('M/d/y');
$this->getCollection()->addAttributeToFilter('special_price', array('neq' => ''))
->addAttributeToFilter('special_from_date', array('date' => true, 'to' => $dateToday))
->addAttributeToFilter('special_to_date', array(
'or'=> array(
0 => array('date' => true, 'from' => $dateToday),
1 => array('is' => new Zend_Db_Expr('null')))
), 'left');
return $this;
}
}