Posted on

Filter a count column in a custom admin grid

I have an admin grid with a count column, everything works fine except the filtering.

This is my _prepareCollection() method :

protected function _prepareCollection()
{
$orders = Mage::getModel(‘Sales/Order’)
->getCollection()
->addFieldToFilter(‘main_table.status’, array(‘eq’ => ‘complete’));

$orders->getSelect()
->joinLeft(
array(
‘sorders’ => ‘suiviprepa_suiviorders’),
‘main_table.increment_id = sorders.order_increment_id ‘,
array(
‘num_issues’ => ‘COUNT(sorders.reason)’
)
)
->group(‘main_table.increment_id’);

$this->setCollection($orders);

return parent::_prepareCollection();
}

In _prepareColumns() I added a filter callback:

$this->addColumn(‘prepa_order_issues’,
array(
‘header’ => ‘Problems’,
‘index’ => ‘num_issues’,
‘type’ => ‘number’,
‘renderer’ => ‘Name_Mymodule_Block_Adminhtml_Orders_Renderer_Numissues’,
‘filter_condition_callback’ => array($this, ‘_prepaIssuesFilter’)
)
);

Like this:

protected function _prepaIssuesFilter($collection, $column)
{
(int) $filterValue = $column->getFilter()->getValue();

if (!is_null($filterValue)) {
$collection->getSelect()->having(‘COUNT(sorders.reason) = ?’, $filterValue);
}
}

The final request is working (if I run it in MySQL is does the job), but Magento returns an error, I guess running another simple request for pagination purpose :

SQLSTATE[42S22]: Column not found: 1054 Unknown column
‘sorders.reason’ in ‘having clause’, query was: SELECT COUNT(*) FROM
`sales_flat_order` AS `main_table` WHERE (main_table.status =
‘complete’) HAVING (COUNT(sorders.reason) = 1)

Does anyone has any idea how to make such a filtering on count column work?

Leave a Reply

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