0

Experimenting with Magento EE 2.1.7. I've created a module which has the means to filter a collection but apparently I'm doing something wrong because I get an "Illegal State" error on the frontend category pages when I include this line prior to return $collection;

$collection->getSize();

While the below code will yield the desired result(s) in the category listing/grid, it fails to reflect the total number of results in pagination or the category product count in toolbar (i.e. There might be a single product on page but 600 products listed in the count and multiple pages of pagination).

<?php

// File: app/code/MyCompany/MyModule/Block/Category/Form.php

namespace MyCompany\MyModule\Block\Category;

class Form extends \Magento\Framework\View\Element\Template
{
    protected $_catalogLayer;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver,
        array $data = []
    ) {
        $this->_catalogLayer = $layerResolver->get();
        parent::__construct($context, $data);
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        $collection = $this->_catalogLayer->getProductCollection();

        $collection->addAttributeToFilter('sku', '123456');

        // This line results in "Illegal state" error on category page.
        $collection->getSize();

        return $collection;
    }
}
  • why are you using $collection->getSize(); as this will return you the total no of records and you are not even using it ? – Priyank Sep 1 '17 at 13:29
  • I was just attempting to get it to work as it seemed be a pre-req for accurate pagination (requires counting of products divided by number to show in grid). I never got beyond including it in the code and having it error out. – sparecycle Sep 1 '17 at 16:21
1
protected $_productCollectionFactory;

public function __construct(
...    
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
...
) {
$this->_productCollectionFactory = $productCollectionFactory;
}

Pass this class inside your __construct() method, and then:

$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToFilter('sku', array('eq' => '123456'));
$size = $collection->getSize();
return $size;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.