Back to Top

How to use Search Criteria to fetch data in Magento2

Updated 23 February 2024

Here we learn, how to use Search Criteria in custom module to fetch data.

We need to create Repository to use Search Criteria in our module. To know how to create Repository in Magento2 Click here

1) Open the Repository Interface Webkul\Hello\Api\TestRepositoryInterface and add new method getList
#File: Webkul/Hello/Api/TestRepositoryInterface.php

<?php
 
namespace Webkul\Hello\Api;
 
interface TestRepositoryInterface
{
    /**
     * Create or update a data
     */
    public function save(\Webkul\Hello\Api\Data\TestInterface $test);
 
    public function getById($testId);

    /**
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Webkul\Hello\Api\Data\TestSearchResultsInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
 
    /**
     * Delete test.
     */
    public function delete(\Webkul\Hello\Api\Data\TestInterface $test);
 
    /**
     * Delete test by ID.
     */
    public function deleteById($testId);
}

2. Create TestsearchResultsInterface.php
File: Webkul/Hello/Api/Data/TestSearchResultsInterface.php

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_Hello
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\Hello\Api\Data;

use Magento\Framework\Api\SearchResultsInterface;

/**
 * Interface for preorder Complete search results.
 * @api
 */
interface TestSearchResultsInterface extends SearchResultsInterface
{
    /**
     * Get test Complete list.
     *
     * @return \Webkul\Hello\Api\Data\TestInterface[]
     */
    public function getItems();

    /**
     * Set test Complete list.
     *
     * @param \Webkul\Hello\Api\Data\TestInterface[] $items
     * @return $this
     */
    public function setItems(array $items);
}

3. Now open TestRepositoryModel.php file and create getList Method.
File: Webkul/Hello/Model/TestRepositoryModel.php

<?php
namespace Webkul\Hello\Model;

use Webkul\Hello\Api\Data;
use Webkul\Hello\Api\TestRepositoryInterface;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\Api\SortOrder;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Reflection\DataObjectProcessor;
use Webkul\Hello\Model\ResourceModel\Test as ResourceTest;
use Webkul\Hello\Model\ResourceModel\Test\CollectionFactory as TestCollectionFactory;
use Magento\Store\Model\StoreManagerInterface;

class TestRepositoryModel implements \Webkul\Hello\Api\TestRepositoryInterface
{
        /**
     * @var ResourceBlock
     */
    protected $resource;

    /**
     * @var BlockFactory
     */
    protected $testFactory;

    /**
     * @var TestCollectionFactory
     */
    protected $testCollectionFactory;

    /**
     * @var Data\BlockSearchResultsInterfaceFactory
     */
    protected $searchResultsFactory;

    /**
     * @var DataObjectHelper
     */
    protected $dataObjectHelper;

    /**
     * @var DataObjectProcessor
     */
    protected $dataObjectProcessor;

    /**
     * @var \Webkul\Hello\Api\Data\TestInterfaceFactory
     */
    protected $dataTestFactory;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    /**
     * @param ResourceTest $resource
     * @param TestFactory $testFactory
     * @param Data\TestInterfaceFactory $dataTestFactory
     * @param TestCollectionFactory $testCollectionFactory
     * @param Data\TestSearchResultsInterfaceFactory $searchResultsFactory
     * @param DataObjectHelper $dataObjectHelper
     * @param DataObjectProcessor $dataObjectProcessor
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        ResourceTest $resource,
        TestFactory $testFactory,
        \Webkul\Hello\Api\Data\TestInterfaceFactory $dataTestFactory,
        TestCollectionFactory $testCollectionFactory,
        Data\TestSearchResultsInterfaceFactory $searchResultsFactory,
        DataObjectHelper $dataObjectHelper,
        DataObjectProcessor $dataObjectProcessor,
        StoreManagerInterface $storeManager
    ) {
        $this->resource = $resource;
        $this->testFactory = $testFactory;
        $this->testCollectionFactory = $testCollectionFactory;
        $this->searchResultsFactory = $searchResultsFactory;
        $this->dataObjectHelper = $dataObjectHelper;
        $this->dataTestFactory = $dataTestFactory;
        $this->dataObjectProcessor = $dataObjectProcessor;
        $this->storeManager = $storeManager;
    }

    /**
     * Load Test data collection by given search criteria
     *
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @param \Magento\Framework\Api\SearchCriteriaInterface $criteria
     * @return \Webkul\Hello\Model\ResourceModel\Test\Collection
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $criteria)
    {
        $searchResults = $this->searchResultsFactory->create();
        $searchResults->setSearchCriteria($criteria);

        $collection = $this->testCollectionFactory->create();
        foreach ($criteria->getFilterGroups() as $filterGroup) {
            foreach ($filterGroup->getFilters() as $filter) {
                $condition = $filter->getConditionType() ?: 'eq';
                $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
            }
        }
        $searchResults->setTotalCount($collection->getSize());
        $sortOrdersData = $criteria->getSortOrders();
        if ($sortOrdersData) {
            foreach ($sortOrdersData as $sortOrder) {
                $collection->addOrder(
                    $sortOrder->getField(),
                    ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
                );
            }
        }
        $collection->setCurPage($criteria->getCurrentPage());

        $collection->setPageSize($criteria->getPageSize());
        
        $testItem = [];
        /** @var Test $testModel */
        foreach ($collection as $testModel) {
            $testData = $this->dataTestFactory->create();
            $this->dataObjectHelper->populateWithArray(
                $testData,
                $testModel->getData(),
                'Webkul\Hello\Api\Data\TestInterface'
            );
            $preorderItem[] = $this->dataObjectProcessor->buildOutputDataArray(
                $testData,
                'Webkul\Hello\Api\Data\TestInterface'
            );
        }
        $searchResults->setItems($testItem);
        return $searchResults;
    }
 
    /**
     * Save test data.
     */
    public function save(\Webkul\Hello\Api\Data\TestInterface $test)
    {
        //your code
    }
    /**
     * Retrieve test data.
     */
    public function getById($testId)
    {
        //your code
    }
 
    /**
     * Delete test.
     */
    public function delete(\Webkul\Hello\Api\Data\TestInterface $test)
    {
        //your code
    }
 
    /**
     * Delete test by test ID.
     */
    public function deleteById($testId)
    {
        //your code
    }
}

Make sure you defined all the data entities in Webkul/Hello/Api/Data/TestInterface and in Webkul/Hello/Model/Test which you want to fetch

Start your headless eCommerce
now.
Find out More

4. Now let’s fetch the data by an example.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$searchCriteriaBuilder = $objectManager->create('Magento\Framework\Api\SearchCriteriaBuilder');
$searchCriteria = $searchCriteriaBuilder->addFilter(
  'test_id',
  1,
  'eq'
)->create();
$items = $this->_completeRepository->getList($searchCriteria);
foreach ($items->getItems() as $value) {
   print_r($value)
}

That’s it.
If any query please comment here.

. . .

Leave a Comment

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


3 comments

  • Abbas
    • Mahesh Singh (Moderator)
  • Ramesh Allamsetti
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home