1 Comment

getProductCount() function returning similar result for every category

handle get request in controller action
getProductCount() function returning similar result for every category

Hello I am trying to get category name and category product count using category Id . In my results I am getting exact category name but product count is duplicating.

foreach ($category as $categoryId) {
    if (!is_null($categoryId)) {
        $categoryLoadData = Mage::getSingleton('catalog/category')->load($categoryId);
        $categoryArray[$count]['id'] = $categoryId;
        $categoryArray[$count]['name'] = $categoryLoadData->getName();
        $categoryArray[$count]['productCount'] = $categoryLoadData->getProductCount();
        Mage::log($categoryId.' - '.$categoryLoadData->getName().' - '.$categoryLoadData->getProductCount(),null,'final.log'
                                . '');
        $count++;
      }
 }
    Mage::log($categoryArray,null,'catrblock.log');

I got result in final.log

14 - category_name_1 - 74
7 - category_name_2 - 74

Result I got in catrblock.log

Array
(
 [0] => Array
 (
     [id] => 14
     [name] => category_name_1
     [productCount] => 74
 )

 [1] => Array
 (
     [id] => 7
     [name] => category_name_2
     [productCount] => 74
 )

)

Related Posts

handle get request in controller action
getProductCount() function returning similar result for every category

1 Comment on this article

  • User November 12, 2016

    To me the problem here is that you’re using a singleton:

    Mage::getSingleton('catalog/category')->load($categoryId);
    

    Thus, even if you reload the singleton in a loop, there can be some persistent data in your object.

    You should use models instead:

    Mage::getModel('catalog/category')->load($categoryId);
    

    If you need clarification about when to use singletons, I reckon you should check this very good SE post:

    http://stackoverflow.com/questions/18756753/magento-getsingleton-vs-getmodel-issue

    Reply

Add a comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax