Skip to content

Instantly share code, notes, and snippets.

@jonatanrdsantos
Created December 17, 2015 13:47
Show Gist options
  • Save jonatanrdsantos/51e34004d684629ed766 to your computer and use it in GitHub Desktop.
Save jonatanrdsantos/51e34004d684629ed766 to your computer and use it in GitHub Desktop.
Magento: Wrong count in admin Grid when using GROUP BY clause, overriding lib module

Magento when you use GROUP BY clause in any Grid.php file in admin, the count always display wrong. Many times it displays 1 even if there are hundreds of records. Due to this your pagination also doesn’t work. This is a bug in Magento. Your getSize() always returns wrong count whereas total records in grid are proper.

To fix this, you need to edit one of your core file. As it’s not a good practice to edit core file, we will here override the core file. Overriding LIB module

Create a rewrite to yout collection main.table:

Mage_[MODULE]Model_Resource[RESOURCENAME]_Grid_Collection

And rewrite getSelectCountSql function with below one:

public function getSelectCountSql()
    {
        $this->_renderFilters();

        $countSelect = clone $this->getSelect();
        $countSelect->reset(Zend_Db_Select::ORDER);
        $countSelect->reset(Zend_Db_Select::LIMIT_COUNT);
        $countSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
        $countSelect->reset(Zend_Db_Select::COLUMNS);

        if(count($this->getSelect()->getPart(Zend_Db_Select::GROUP)) > 0) {
            $countSelect->reset(Zend_Db_Select::GROUP);
            $countSelect->distinct(true);
            $group = $this->getSelect()->getPart(Zend_Db_Select::GROUP);
            $countSelect->columns("COUNT(DISTINCT ".implode(", ", $group).")");
        } else {
            $countSelect->columns('COUNT(*)');
        }
        return $countSelect;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment