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];
}
}