Magento – Magento2 – addAttributeToFilter wrong pagination

collection;magento2product-collection

I'm creating an extension that filters the product collection. The filter works perfect, but it looks like pagination is not updated. I see 6 pages, but on page 2 the page is already empty.

Here's my code:

Register the plugin:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
        <plugin name="sidebarFilters" type="Silvan\Sidebar\Model\Plugin\SidebarFilter"/>
    </type>
</config>

The plugin:

public function aroundAddFieldToFilter(ProductCollection $collection, \Closure $proceed, $fields, $condition = null)
{
    if ( $fields === 'category_ids' )
    {
        // Get brand
        $brands = isset($_GET[ 'brands' ]) ? $_GET[ 'brands' ] : false;

        if ( $brands )
        {
            $brands = array_map(function($brand) {
                return urldecode($brand);
            }, $brands);

            $collection->addAttributeToFilter('brand', ['in' => $brands]);
        }
    }

    /** Do not try to pass empty $fields to addFieldToFilter, it will cause exception */
    return $fields ? $proceed($fields, $condition) : $collection;
}

Does anyone have a clue?

Best Answer

You need use public addFieldToFilter to pass parameters to fulltext search. Try write you code like:

public function aroundAddFieldToFilter(ProductCollection $collection, \Closure $proceed, $fields, $condition = null)
{
    if ( $fields === 'category_ids' )
    {
        // Get brand
        $brands = isset($_GET[ 'brands' ]) ? $_GET[ 'brands' ] : false;

        if ( $brands )
        {
            $brands = array_map(function($brand) {
                return urldecode($brand);
            }, $brands);

            // $collection->addAttributeToFilter('brand', ['in' => $brands]);
            $proceed('brand', $brands);
        }
    }

    /** Do not try to pass empty $fields to addFieldToFilter, it will cause exception */
    return $fields ? $proceed($fields, $condition) : $collection;
}