Magento 2 – Fix Catalog Filter Issue in Frontend

magento-2.1magento2product-collectionxml

I have filter catalog product collection based customer logged in frontend, Using event observer catalog_block_product_list_collection, Filter working fine. But the issue is found in Layered navigation and pagination count and won't be update or changes count based on filter applied.

Can anyone help me how can I resolved and what changes need to done further.
enter image description here

Best Answer

Try it.

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        //Current customer id
        $customerSession = $objectManager->create('\Magento\Customer\Model\Session');
        $cid = $customerSession->getCustomer()->getId();

        $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');

        $productCollection->addAttributeToSelect('*');
        $productCollection->addAttributeToFilter(
                array(
                    array('attribute'=>'allowed_customers', 'like'=>$cid.',%'),
                    array('attribute'=>'allowed_customers', 'like'=>'%,'.$cid.',%'),
                    array('attribute'=>'allowed_customers', 'like'=>'%,'.$cid),
                    array('attribute'=>'allowed_customers', 'like'=>'%'.$cid),
                    array('attribute'=>'allowed_customers', 'like'=>'%'.$cid.'%'),
                    array('attribute'=>'allowed_customers', 'like'=>$cid.'%')));

        $productCollection->load();

        $skus = $productCollection->getColumnValues('sku');
        $skus = array_unique($skus);

        //$skus = array('24-MB04', '24-MB03', '24-MB02');

        $this->filterBuilder->setField('sku');
        $this->filterBuilder->setValue($skus);
        $this->filterBuilder->setConditionType('in');

        $this->searchCriteriaBuilder->addFilter($this->filterBuilder->create());