Skip to content

Instantly share code, notes, and snippets.

@0-Sony
Created January 14, 2021 11:22
Show Gist options
  • Save 0-Sony/cdbc03f7108b036c7503f75b8995a2dc to your computer and use it in GitHub Desktop.
Save 0-Sony/cdbc03f7108b036c7503f75b8995a2dc to your computer and use it in GitHub Desktop.
Magento 2 : Filter product using search criteria
<?php
namespace MyNamespace\MyModule\Model;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Api\ProductRepositoryInterface;
class ProductFilter
{
/** @var ProductRepositoryInterface */
protected $productRepository;
/** @var SearchCriteriaBuilder */
protected $searchCriteriaBuilder;
/**
* Initialize dependencies.
*
* @param ProductRepositoryInterface $productRepository
* @param SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
/**
* Get products with filter.
*
* @param string $fieldName
* @param string $fieldValue
* @param string $filterType
* @return \Magento\Catalog\Api\Data\ProductInterface[]
*/
public function getProducts($fieldName, $fieldValue, $filterType)
{
$searchCriteria = $this->searchCriteriaBuilder->addFilter($fieldName, $fieldValue, $filterType)->create();
$products = $this->productRepository->getList($searchCriteria);
return $products->getItems();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment