Magento – Magento 2 no Layered Navigation after filter collection

catalogmagento2product

We've added a default filter for our product collection by adding a plugin:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Model\Layer">
        <plugin name="filterCatalog" type="Silvan\StockStatus\Plugin\Catalog\Model\Layer" sortOrder="10"/>
    </type>
</config>

And the class:

<?php namespace Silvan\StockStatus\Plugin\Catalog\Model;

class Layer
{
    /**
     * afterGetProductCollection method
     *
     * @param                                                                $subject
     * @param \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $collection
     *
     * @return mixed
     */
    public function afterGetProductCollection($subject, $collection)
    {
        $collection->addAttributeToSelect('bgs_stock_status');
        $collection->addAttributeToFilter(
            [
                ['attribute' => 'bgs_stock_status', 'is' => new \Zend_Db_Expr('null')],
                ['attribute' => 'bgs_stock_status', 'lt' => 3],
            ]);

        $collection->getSize();

        return $collection;
    }
}

But as soon as we add the 'addAttributeToFilter' part, all Layered Navigation filter options are gone. If we remove this code it's shown again.

How can we filter our product collection, without losing the filter attributes? There are enough products to show filters.

UPDATE

I found out that the moment I add this filter, an error is thrown: https://www.dropbox.com/s/y71a032fe3n1pvr/Schermafbeelding%202017-11-30%20om%2010.21.17.png?dl=0

The filter does work fine, only this error is the real cause that the filter attributes don't show up.

Best Answer

Use addAttributeToFilter like this:

<?php 
namespace Silvan\StockStatus\Plugin\Catalog\Model;

class Layer
{
    /**
     * afterGetProductCollection method
     *
     * @param                                                                $subject
     * @param \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $collection
     *
     * @return mixed
     */
    public function afterGetProductCollection($subject, $collection)
    {
        $collection->addAttributeToSelect('bgs_stock_status');

        $collection->addAttributeToFilter(
        'bgs_stock_status', 
             array('lt' => 3)
             array('null' => TRUE)
        );

        $collection->getSize();

        return $collection;
    }
}
Related Topic