2

I'm migrating Magento 2.3 to 2.4.5. Already I have a working feature of a custom attribute filter in the Product list page also having a plugin but the class Magento\CatalogSearch\Model\Search\IndexBuilder doesn't exist in Magento 2.4 for elastic search 7.

<type name="Magento\CatalogSearch\Model\Search\IndexBuilder">
        <plugin name="search_index_builder_restrict_product_after_get" type="Vendor\RestrictProduct\Plugin\CatalogSearch\Search\IndexBuilder" />
</type>

Also applied the same logic here for

<type name="Magento\Elasticsearch7\Model\Client\Elasticsearch">
        <plugin name="search_es_restrict_product_after_get" type="Vendor\RestrictProduct\Plugin\ElasticLayerPlugin" />
</type>

But the custom filter is not working. My Vendor\RestrictProduct\Plugin\ElasticLayerPlugin is below

<?php
namespace Vendor\RestrictProduct\Plugin;

use Magento\Elasticsearch7\Model\Client\Elasticsearch;

class ElasticLayerPlugin
{
    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $productCollectionFactory;


    protected $request;

    /**
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
     */
    public function __construct(
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->customerSession = $customerSession;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->request = $request;
    }

    public function beforeQuery($subject,$query) {

        $customer = $this->customerSession->getCustomer();
        $customerGroupId = 0;
        if ($customer->getData()) {
            $customerGroupId = (int)$customer->getGroupId();
        }

        $filteredIds = $this->productCollectionFactory->create()
            ->addAttributeToSelect('*');

        if($customerGroupId>4) { 
            $filteredIds->addAttributeToFilter([
                                ['attribute' => 'customer_group', ['finset' => (int)$customerGroupId]],
                                ['attribute' => 'customer_group', ['finset' => 4]]]);

        } else {
            $filteredIds->addAttributeToFilter('customer_group', ['finset' => (int)$customerGroupId]);
        }

        if($this->request->getFullActionName()=='catalog_category_view') {      
            $filteredIds->addAttributeToFilter('sku', ['neq' => '6191']);
        }

        $filteredIds = $filteredIds->getAllIds();

        // This is where to fetch the entity_id array to filter the Elastic collection with
        //$filteredIds   = [3916];

        if(!$filteredIds || count($filteredIds) < 1)  {

            return [$query];
        }

        // Add the entity_id filter to the Elastic collection
        $query['body']['query']['bool']['filter'] = ['ids' => [ 'values' => $filteredIds]];


        return [$query];

    }
}
4
  • Can you share few more details on what exactly you mean by "custom filter is not working" Also can you plz share the content of this file Vendor\RestrictProduct\Plugin\CatalogSearch\Search\IndexBuilder and the custom attribute configuration. Oct 29, 2022 at 16:38
  • is your custom plugin calling when you go to listing page? Oct 31, 2022 at 5:25
  • custom filter in the sense I have a custom attribute and I'll filter by value
    – Ramesh KR
    Oct 31, 2022 at 5:27
  • Magento\Elasticsearch7\Model\Client\Elasticsearch Yes this plugin is called in listpage. @RizwanKhan
    – Ramesh KR
    Oct 31, 2022 at 5:28

1 Answer 1

3

There is no issues with that plugin, as I tried the same plugin in a vanilla Magento and tried a custom filter, it is working as expected.

Plugin code:

app/code/Vendor/Module/etc/frontend/di.xml

<?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\Elasticsearch7\Model\Client\Elasticsearch">
        <plugin name="search_es_restrict_product_after_get" type="Vendor\Module\Plugin\ElasticLayerPlugin" />
    </type>
</config>

Vendor\Module\Plugin\ElasticLayerPlugin

<?php
namespace Vendor\Module\Plugin;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Request\Http;

class ElasticLayerPlugin
{
    /**
     * @var CollectionFactory
     */
    protected $productCollectionFactory;

    protected $request;

    /**
     * @param CollectionFactory $productCollectionFactory
     * @param Http $request
     */
    public function __construct(
        CollectionFactory $productCollectionFactory,
        Http $request
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->request = $request;
    }

    public function beforeQuery($subject, $query)
    {
        $filteredIds = $this->productCollectionFactory->create()
            ->addAttributeToSelect('*');

        /**
         * Configured 15, 19 activities in magento admin panel and tried to filter the results
         * 15 => Cycling
         * 19 => Overnight
         * */
        
        $filteredIds->addAttributeToFilter([
            ['attribute' => 'activity', ['finset' => 15]],
            ['attribute' => 'activity', ['finset' => 19]]]);

        if ($this->request->getFullActionName()=='catalog_category_view') {
            $filteredIds->addAttributeToFilter('sku', ['neq' => '6191']);
        }

        $filteredIds = $filteredIds->getAllIds();
        

        if (!$filteredIds || count($filteredIds) < 1) {
            return [$query];
        }
        
        $query['body']['query']['bool']['filter'] = ['ids' => [ 'values' => $filteredIds]];

        return [$query];
    }
}

Result:

Before filter enter image description here

After Filter

enter image description here

I filtered the products by the "activity" attribute, and it is working as expected.

I hope there is some issue with your data, so that's why the custom filter is not working properly.

Possibilities for issues:

  1. There is an issue with CustomerSession, it may not fetch the current customer details, pls make sure the customer details by logging the data

  2. Maybe any other third-party modules like Amasty override the native Magento\Elasticsearch7\Model\Client\Elasticsearch class, so pls make sure the plugins sort order

  3. Log the $filteredIds before adding it into the filter, and check whether are you getting the expected result or not.

I hope it will help you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.