Introduction

In Magento 2, handling collections efficiently is crucial for performance and flexibility. One of the most effective ways to filter, sort, and retrieve collections is by using the SearchCriteriaBuilder. Despite its importance in Magento 2’s core architecture, many developers find it underutilized or unfamiliar. This guide will walk you through the step-by-step process of using SearchCriteriaBuilder to get collections in Magento 2.

What is SearchCriteriaBuilder?

The SearchCriteriaBuilder is a part of Magento’s Service Contracts and is used to define search criteria for fetching filtered and sorted data from repositories. This method allows for clean and reusable code by abstracting complex queries into a simple API.

Understanding Search Criteria

Search Criteria in Magento 2 represents the conditions and rules that you apply to filter and fetch data. These criteria can include filters, sort orders, and pagination settings, making it a versatile tool for managing data retrieval.

Step-by-Step Guide to Using SearchCriteriaBuilder

Step 1: Injecting Dependencies

To begin, you need to inject the SearchCriteriaBuilder class and the repository interface of the entity you want to fetch. For example, if you want to retrieve a product collection, you should inject Magento\Catalog\Api\ProductRepositoryInterface.

namespace TechnicalMrStar\Catalog\Model;

use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Api\ProductRepositoryInterface;

class Example
{
    protected $searchCriteriaBuilder;
    protected $productRepository;

    public function __construct(
        SearchCriteriaBuilder $searchCriteriaBuilder,
        ProductRepositoryInterface $productRepository
    ) {
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->productRepository = $productRepository;
    }
}

Step 2: Adding Filters

Filters are the conditions applied to the collection. You can add one or multiple filters using the addFilter method, specifying the field name, value, and condition.

$searchCriteria = $this->searchCriteriaBuilder
    ->addFilter('status', 1, 'eq')  // Filter products with status enabled
    ->addFilter('visibility', 4, 'eq')  // Filter products visible in catalog and search
    ->create();

Step 3: Setting Sorting and Pagination

Sorting and pagination can be defined using the setPageSize, setCurrentPage, and addSortOrder methods to ensure that data is retrieved in a specific order and within certain limits.

$searchCriteria = $this->searchCriteriaBuilder
    ->setPageSize(20)  // Limit results to 20 items per page
    ->setCurrentPage(1)  // Start from the first page
    ->addSortOrder('name', 'ASC')  // Sort results by product name in ascending order
    ->create();

Step 4: Retrieving the Collection

Once the search criteria are built, use the repository’s getList method to fetch the collection based on the criteria defined.

$products = $this->productRepository->getList($searchCriteria);
return $products->getItems();  // Returns an array of product objects

Full Example Code

Below is a complete example demonstrating how to implement the above steps in a single method:

namespace TechnicalMrStar\Catalog\Model;

use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Catalog\Api\ProductRepositoryInterface;

class Example
{
    protected $searchCriteriaBuilder;
    protected $productRepository;

    public function __construct(
        SearchCriteriaBuilder $searchCriteriaBuilder,
        ProductRepositoryInterface $productRepository
    ) {
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->productRepository = $productRepository;
    }

    public function getFilteredProducts()
    {
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('status', 1, 'eq')
            ->addFilter('visibility', 4, 'eq')
            ->setPageSize(20)
            ->setCurrentPage(1)
            ->addSortOrder('name', 'ASC')
            ->create();

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

Conclusion

Using SearchCriteriaBuilder is an essential skill for any Magento 2 developer. It allows you to build powerful, flexible, and reusable queries that interact directly with Magento’s service layer. By mastering this tool, you can create cleaner code and ensure your Magento 2 projects are easier to maintain and extend.

Final Thoughts

Whether you’re filtering products, organizing customer data, or implementing complex search functionalities, SearchCriteriaBuilder offers a robust solution for managing data in Magento 2. Experiment with different filters, sorting, and pagination to fully understand its capabilities. Happy coding!

Rate this post