2

How to convert

 $products = $this->_catalogSearchAdvanced
        ->getProductCollection()
        ->addStoreFilter($storeId)
        ->setCurPage($page)
        ->setPageSize($pageSize)
        ->setOrder($searchOrder, $searchDir)
        ->addAttributeToFilter(
            array(
                array('attribute' => 'name', 'like' => '%' . $searchTerm . '%'),
                array('attribute' => 'description', 'like' => '%' . $searchTerm . '%'),
            )); 

for get the same result using SearchCriteria and ProductRepository?

1 Answer 1

7

I'm not test yet but it should work

public function __construct(
    ProductRepositoryInterface $productRepository,
    SearchCriteriaBuilder $searchCriteriaBuilder,
    FilterBuilder $filterBuilder,
    \Magento\Framework\Api\SortOrderBuilder $sortOrderBuilder
) {
    $this->productRepository = $productRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder = $filterBuilder;
    $this->sortOrderBuilder = $sortOrderBuilder;
}

public function getProducts()
{

    //use Magento\Framework\Api\SortOrder;
    $filters[] = $this->filterBuilder->setField('search_term')
        ->setValue($searchTerm)
        ->create();

    // Add another field filter
    $filters[] = $this->filterBuilder->setField('another_field')
        ->setValue($value)
        ->create();

    $this->searchCriteriaBuilder->addFilters($filters);
    $sortOrder = $this->sortOrderBuilder->setField('field_name')->setDirection(SortOrder::SORT_ASC)->create();
    $this->searchCriteriaBuilder->setSortOrders([$sortOrder]);
    $searchCriteria = $this->searchCriteriaBuilder->setCurrentPage(1)->setPageSize(10)->create();
    $searchResults = $this->productRepository->getList($searchCriteria);
    return $searchResults->getItems();
}
4
  • and you know how to use the other properties? current page, page size, order, attribute = value, etc?
    – Miguel
    Commented Jun 26, 2017 at 7:37
  • Updated my answer
    – mrtuvn
    Commented Jun 26, 2017 at 10:38
  • addFilter(array filters) to searchCriteria dont exist..
    – Miguel
    Commented Jun 26, 2017 at 15:30
  • 1
    Hmm, I do not see storeId filter.
    – Macas
    Commented Oct 4, 2021 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.