:::: MENU ::::

Creating a Search Criteria with Null Condition in Magento 2

0.00 avg. rating (0% score) - 0 votes

Magento 2 provides a powerful API that allows you to create custom search criteria for querying data from various entities in your Magento store. When building search criteria, you may need to filter records based on whether a particular field has a null value or not.

In this post, we’ll show you how to create a search criteria with a null condition using the FilterBuilder class in Magento 2.

To get started, you’ll need to inject two dependencies into your class:

Magento\Framework\Api\SearchCriteriaBuilder
Magento\Framework\Api\FilterBuilder

These dependencies are used to build the search criteria and filter objects, respectively.

use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\FilterBuilder;

class MyCustomClass
{
    protected $searchCriteriaBuilder;
    protected $filterBuilder;

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

    // ...
}

Next, you can use the class FilterBuilder to create a filter object with a null condition by calling the setConditionType method and passing null as the argument. You also need to set the name of the field you want to filter on using the setField method.

Finally, you can add the filter to your search criteria object by calling the addFilters method of the SearchCriteriaBuilder class.

public function buildSearchCriteria()
{
    $filter = $this->filterBuilder
        ->setField('field_name')
        ->setConditionType('null')
        ->create();

    $searchCriteria = $this->searchCriteriaBuilder
        ->addFilters([$filter])
        ->create();

    return $searchCriteria;
}

In the example above, we’re using the field_name placeholder to represent the name of the field you want to filter on. You can replace this with the actual name of the field in your code.

Note that if you want to search for fields that are not null, you can use the notnull condition type instead of null.

In conclusion, creating a search criteria with a null condition in Magento 2 is a straightforward process that can be achieved using the FilterBuilder and SearchCriteriaBuilder classes. By following the steps outlined in this post, you can easily filter records based on whether a field has a null value or not.




Hey! Qué opinas sobre el artículo?