Created
January 14, 2021 11:22
-
-
Save 0-Sony/cdbc03f7108b036c7503f75b8995a2dc to your computer and use it in GitHub Desktop.
Magento 2 : Filter product using search criteria
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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