Skip to content

Custom Product Filter GraphQl Not working in magento 2.4

I want to add a stock filter for the product search GraphQl query. check below my code

schema.graphqls

input ProductAttributeFilterInput @doc(description: "Defines the filters"){
    stock_status: FilterEqualTypeInput
}

di.xml

   <virtualType name="MagentoCatalogModelApiSearchCriteriaCollectionProcessorProductFilterProcessor" type="MagentoEavModelApiSearchCriteriaCollectionProcessorFilterProcessor">
        <arguments>
            <argument name="customFilters" xsi:type="array">
                <item name="stock_status" xsi:type="object">CustomModuleModelResolverProductsSearchCriteriaCollectionProcessorFilterProcessorCustomStockFilter</item>
            </argument>
        </arguments>
    </virtualType>

CustomStockFilter.php

<?php
namespace CustomModuleModelResolverProductsSearchCriteriaCollectionProcessorFilterProcessor;

use MagentoCatalogModelResourceModelProductCollection;
use MagentoFrameworkApiFilter;
use MagentoFrameworkApiSearchCriteriaCollectionProcessorFilterProcessorCustomFilterInterface;
use MagentoFrameworkDataCollectionAbstractDb;

class CustomStockFilter implements CustomFilterInterface
{

    private $logger;
    private $stock;

    public function __construct(
        PsrLogLoggerInterface $logger,
        MagentoCatalogInventoryHelperStock $stock
    ) {
        $this->logger = $logger;
        $this->stock = $stock;
    }


    /**
     * Apply filter by 'category_id' to product collection.
     *
     * For anchor categories, the products from all children categories will be present in the result.
     *
     * @param Filter $filter
     * @param AbstractDb $collection
     * @return bool Whether the filter is applied
     */
    public function apply(Filter $filter, AbstractDb $collection)
    {
        $this->logger->info('stock filter log');
        $conditionType = $filter->getConditionType();
        $value = $filter->getValue();
        $this->stock->addInStockFilterToCollection($collection);
        
        return true;
    }

}

GraphQL Query

{
  products(
    search: "test"
    filter: { stock_status: { in: ["1"] } }
  ) {
    items {
      uid
    }
  }
}

I added a logger in the resolver file but the resolver is not triggered. my Magento ver. 2.4.4-p1.

how to add in-stock/outstock filter in product search query.

stock_status I added a custom field but its not working

please help me on this