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?

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
    Jun 26 '17 at 7:37
  • Updated my answer
    – mrtuvn
    Jun 26 '17 at 10:38
  • addFilter(array filters) to searchCriteria dont exist..
    – Miguel
    Jun 26 '17 at 15:30
  • Hmm, I do not see storeId filter.
    – Macas
    Oct 4 '21 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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