0

I am trying to Modify Product collection which provides collection for product listing page aka category page. For this I have overridden _getProductCollection function of Magento\Catalog\Block\Product\ListProduct. In that function I am trying to do something like below:

if ($this->_productCollection === null) {
            $this->_productCollection = $this->initializeProductCollection();
        }
        $productIds = array();
        foreach($this->_productCollection as $key=>$product)
        {
            $_product = $this->helper->getProduct($product->getId()); // called custom helper function to load product
            if($_product->getAttrCode() !='' && $_product->getAttrCode() == 1)
            {
                $productIds[] = $_product->getId();
            }
        }
        $this->_productCollection->addFieldToFilter('entity_id', array('in'=>$productIds));
        return $this->_productCollection;

In system.log file, It shows this error - main.CRITICAL: Illegal state [] []

1

Not sure what you are trying to achieve, but I can tell you where it fails.
Once you iterate through the product collection foreach($this->_productCollection as $key=>$product) the sql query that retrieves the products is executed and any other filter you add to the collection after this, is useless. It has no effect.
I also see that you are loading each product in the collection separately. This increases the execution time and the resources used by your script.
From what I see in your code, you are trying to filter a collection based on attr_code.
I think you can achieve this by marking the attribute used_in_product_listing from the backend and just adding

$this->_productCollection->addAttributeToFilter('attr_code', 1);

  • Not getting attr_code in $this->_productCollection even after enabling used_in_product_listing that's why I did that. – mighty_hk Jul 2 '18 at 7:50
  • rebuild the indexes – Marius Jul 2 '18 at 8:05
  • Still not working. – mighty_hk Jul 2 '18 at 8:10
0

Try this :

if ($this->_productCollection === null) {
    $this->_productCollection = $this->initializeProductCollection();
}
$productIds = array();
foreach($this->_productCollection as $key=>$product)
{
    $_product = $this->helper->getProduct($product->getId()); // called custom helper function to load product
    $attrCode =$_product->getResource()->getAttribute('attr_code')->getFrontend()->getValue($_product);
    if($attrCode !='' && $attrCode == 1)
    {
        $productIds[] = $_product->getId();
    }
}
$this->_productCollection->addFieldToFilter('entity_id', array('in'=>$productIds));
return $this->_productCollection;
  • No, not working. – mighty_hk Jul 2 '18 at 8:25

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.