How to use Search Criteria for the custom collection in Magento 2?
How to use Search Criteria for the custom collection in Magento 2?

How to use Search Criteria for the custom collection in Magento 2?

In this article, I will show you, how you can use Search Criteria in the custom collection.

Search Criteria is an implementation of the SearchCriteriaInterface class that allows you to build custom requests with different conditions. You can read more at devdoc for Search Criteria Searching with Repositories

1. Here we use getList() method to get custom collection with Search Criteria

Add new method getList() in your Repository Interface Mageprince\Test\Api\TestRepositoryInterface and add new method

File: Mageprince/Test/Api/TestRepositoryInterface.php

namespace Mageprince\Test\Api;

namespace Mageprince\Test\Api;
 
interface TestRepositoryInterface
{
    /**
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Mageprince\Test\Api\Data\TestSearchResultsInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
}

2. Now create TestsearchResultsInterface.php

File: Mageprince/Test/Api/Data/TestSearchResultsInterface.php

namespace Mageprince\Test\Api\Data;

use Magento\Framework\Api\SearchResultsInterface;

/**
 * @api
 */
interface TestSearchResultsInterface extends SearchResultsInterface
{
    /**
     * Get items
     * @return \Mageprince\Test\Api\Data\TestInterface[]
     */
    public function getItems();

    /**
     * Set items
     * @param \Mageprince\Test\Api\Data\TestInterface[] $items
     * @return $this
     */
    public function setItems(array $items);
}

3. Add preference for TestSearchResultsInterface

File: app/code/Mageprince/Test/etc/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Mageprince\Test\Api\TestRepositoryInterface" type="Mageprince\Test\Model\TestRepositoryModel" />
    <preference for="Mageprince\Test\Api\Data\TestInterface" type="Mageprince\Test\Model\Test" />
    <preference for="Mageprince\Test\Api\Data\TestSearchResultsInterface" type="Magento\Framework\Api\SearchResults" />
</config>

4. Now create getList() Method in TestRepositoryModel.php

File: Mageprince/Test/Model/TestRepositoryModel.php

namespace Mageprince\Test\Model;

use Mageprince\Test\Api\Data\TestInterface;

class TestRepositoryModel implements \Mageprince\Test\Api\TestRepositoryInterface
{
    /**
     * @var \Mageprince\Test\Model\ResourceModel\Test\CollectionFactory
     */
    protected $testCollectionFactory;

    /**
     * @var \Mageprince\Test\Api\Data\TestSearchResultsInterfaceFactory
     */
    protected $searchResultsFactory;


    public function __construct(
        \Mageprince\Test\Model\ResourceModel\Test\CollectionFactory $testCollectionFactory,
        \Mageprince\Test\Api\Data\TestSearchResultsInterfaceFactory $searchResultsFactory
    ) {
        $this->testCollectionFactory = $testCollectionFactory;
        $this->searchResultsFactory = $searchResultsFactory;
    }

    /**
     * @inheritdoc
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
    {
        $searchResults = $this->searchResultsFactory->create();
        $searchResults->setSearchCriteria($searchCriteria);
        $collection = $this->testCollectionFactory->create();
        foreach ($searchCriteria->getFilterGroups() as $filterGroup) {
            foreach ($filterGroup->getFilters() as $filter) {
                $condition = $filter->getConditionType() ?: 'eq';
                $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
            }
        }
        $searchResults->setTotalCount($collection->getSize());
        $sortOrdersData = $searchCriteria->getSortOrders();
        if ($sortOrdersData) {
            foreach ($sortOrdersData as $sortOrder) {
                $collection->addOrder(
                    $sortOrder->getField(),
                    ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
                );
            }
        }

        $collection->setCurPage($searchCriteria->getCurrentPage());
        $collection->setPageSize($searchCriteria->getPageSize());
        $searchResults->setItems($collection->getData());
        return $searchResults;
    }
}

We must define all data entities in test Mageprince/Test/Api/Data/TestInterface  with model Mageprince/Test/Model/Test which we use for custom collection

5. Here is the example of getting data with SearchCriteria

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$searchCriteriaBuilder = $objectManager->create('Magento\Framework\Api\SearchCriteriaBuilder');
$searchCriteria = $searchCriteriaBuilder->addFilter('custom_id', 12, 'eq')->create();

/** @var Mageprince\Test\Api\TestRepositoryInterface */
$items = $this->testRepositoryInterface->getList($searchCriteria);

foreach ($items->getItems() as $item) {
   print_r($item); //Item data
}

Here is the screenshot of postman collection of getting custom collection by Search Criteria with Rest API

I hope this article will use to get custom collection by Search Criteria. If you like this post please share it with the following share links. Happy Coding…:)