4

I've successfully override productList block to show my custom filtered product collection like this:

di.xml

<preference for="\Magento\Catalog\Block\Product\ListProduct" type="\Vendor\Module\Block\Product\ListProduct"/>

Vendor\Module\Block\Product\ListProduct

protected function _getProductCollection()
{
    $productCollection = parent::_getProductCollection(); 
    if(isset($_GET['custom_input'])){
      if(!empty($_GET['custom_input']){
        $customInput = $_GET['custom_input'];
        $productCollection = $this->myModuleHelper->filterProduct(customInput, productCollection);
      }
    }
    $this->_productCollection = $productCollection;
    $this->_productCollection->getSize();
    return $proCollection;
}

but the layered navigation options not showing the right option and product count like the image below:

example failed result

0

For making the product collection compatible with the layered nevigation you can follow below code -

protected function _getProductCollection() 
{ 
if ($this->_productCollection === null) 
{ 
$layer = $this->getLayer(); 
if ($this->getShowRootCategory()) 
{ 
$this->setCategoryId($this->_storeManager->getStore()->getRootCategoryId()); 
}





        if ($this->_coreRegistry->registry('product')) {
          $categories = $this->_coreRegistry->registry('product')
                    ->getCategoryCollection()->setPage(1, 1)
                    ->load();
          if ($categories->count()) {
              $this->setCategoryId(current($categories->getIterator()));
          }
        }
        $origCategory = null;
        if ($this->getCategoryId()) {
          try {
              $category = $this->categoryRepository->get($this->getCategoryId());
          } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
              $category = null;
          }
          if ($category) {
              $origCategory = $layer->getCurrentCategory();
              $layer->setCurrentCategory($category);
          }
        }

        $productcollection = $layer->getProductCollection();
        /* you may apply the your custom filter on this product collection */


        $this->_productCollection = $productcollection;
        $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

        if ($origCategory) {
          $layer->setCurrentCategory($origCategory);
        }
    } 
    $this->_productCollection->getSize();
    return $this->_productCollection;
}

In your code neither you are getting the product collection from layer and nor assigning the same to category. For reference you may follow the core block - Magento\Catalog\Block\Product\ListProduct

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.