Working with Search Criteria to fetch Data in Magento2

Here I am going to explain that how we can use search criteria to fetch data from repository as per our requirement. Before going to explain, I want to say one thing that we can use search criteria with those repositories which have getList() method into their interface. Into custom module, If there are repositry interface defined, then we can use search criteria also there.

First, we will discuss in brief about all parts of Search Criteria to better understand.

Filter: This filter class is smallest part of Search Criteria. This is use to define to filter condition of custom field like given below.

$filter = $this->filterBuilder
            ->setField(fieldName)
            ->setValue(fieldValue)
            ->setConditionType(filterType)           
            ->create();
 

In filter type, we can use given below filter operator as per requirement.

 "eq" => equalValue
 "neq" => notEqualValue
 "like" => likeValue
 "nlike" => notLikeValue
 "is" => isValue
 "in" => inValues
 "nin" => notInValues
 "notnull" => valueIsNotNull
 "null" => valueIsNull
 "moreq" => moreOrEqualValue
 "gt" => greaterValue
 "lt" => lessValue
 "gteq" => greaterOrEqualValue
 "lteq" => lessOrEqualValue
 "finset" => valueInSet
 "from" => fromValue, "to" => toValue

Filter Group: This FilterGroup Class is used for combining more filters into a group with ‘OR’ condition and Filter groups are combined into Search Criteria with ‘And’ condition. See given below combination of Filter Groups.

$filter1 = $this->filterBuilder
    ->setField("url")
    ->setValue("%magento.com")
    ->setConditionType("like")
     ->create();

$filter2 = $this->filterBuilder
    ->setField("store_id")
    ->setValue("1")
    ->setConditionType("eq")
    ->create();

For 'OR' condition between two filter fields
 $filter_group = $this->filterGroupBuilder
            ->addFilter($filter_1)
            ->addFilter($filter_2)
            ->create();
 
        // add filter group to setFilterGroups()
        $searchCriteria = $this->searchCriteriaBuilder
            ->setFilterGroups([$filter_group])
            ->create();

For 'AND' condition between two filter fields

$filter_group1 = $this->filterGroupBuilder
            ->addFilter($filter_1)           
            ->create();

$filter_group2 = $this->filterGroupBuilder
            ->addFilter($filter_1)            
            ->create();

 // add filter group to setFilterGroups()
  $searchCriteria = $this->searchCriteriaBuilder
            ->setFilterGroups([$filterGroup1, $filterGroup2)
            ->create();

Sorting: For sorting into Search Criteria, we will use SortOrder class.

$sortOrder = $this->sortOrderBuilder
->setField('weight')
->setDirection('DESC')
->create();
$this->searchCriteriaBuilder->addSortOrder($sortOrder);

For Multiple Sort Orders

$sortOrder2 = $this->sortOrderBuilder
->setField('sku')
->setDirection('DESC')
->create();
$this->searchCriteriaBuilder->setSortOrders([$sortOrder,$sortOrder2]);

Pagination: For pagination, we can use setPageSize() and setCurrentPage() function with Search Criteria.

// Get the first 10 records
$this->searchCriteriaBuilder
->setPageSize(10)
->setCurrentPage(1);

Now we have discussed about all parts of Search Criteria. Let’s put all together into Product Search List. I have used all parts of Search Criteria into a block file.

<?php
namespace BrijeshTech\Custom\Block;
class Product extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\Api\FilterBuilder $filterBuilder,
\Magento\Framework\Api\Search\FilterGroupBuilder $filterGroupBuilder,
\Magento\Framework\Api\Search\SortOrderBuilder $sortOrderBuilder,
array $data = []
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->filterBuilder = $filterBuilder;
$this->filterGroupBuilder = $filterGroupBuilder;
$this->sortOrderBuilder = $sortOrderBuilder;
parent::__construct($context, $data);
}

/**
Get Product List
*/
public function getProductList() {
$filter1 = $this->filterBuilder
->setField('sku')
->setConditionType('like')
->setValue('MSH01%')
->create();
$filter2 = $this->filterBuilder
->setField('type_id')
->setConditionType('eq')
->setValue('simple')
->create();
$filter_group = $this->filterGroupBuilder
->addFilter($filter1)
->addFilter($filter2)
->create();
// add filter group to setFilterGroups()

$sortOrder = $this->sortOrderBuilder
->setField('weight')
->setDirection('DESC')
->create();

$searchCriteria = $this->searchCriteriaBuilder
->setFilterGroups([$filter_group])
->addSortOrder($sortOrder)
->setPageSize(10)
->setCurrentPage(1)
->create();
/**
For Single Filter or For 'AND' Condition between Filtes, we can go without Filter group. See given below
**/
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('sku','MSH01%', 'like')
->addFilter('type_id','simple', 'eq')
->addSortOrder($sortOrder)
->setPageSize(10)
->setCurrentPage(1)
->create();

$products = $this->productRepository->getList($searchCriteria)->getItems();
return $products;
}
}

Hope, This article will help you to easily work with Search Criteria and Repository. Fetching data from Repository is preferable way according to Magento.

References: For going into more depth, you can check given below URL.

Leave a Reply

Your email address will not be published. Required fields are marked *