1

I generated a custom extension with a custom model collection from mage2gen , is it possible to implement the search_criteria like when you retrieve product using rest api? what i know is the product model will use getList function to filter collection by search_criteria:

$this->procudtRepository->getList($searchCriteria);

if i have a post input with parameter search_criteria like this:

'searchCriteria' => [
  'page_size'=> 3,
  'current_page'=> 15,
  'filterGroups' => [
    0 => [
      'filters' => [
         0 => [
           'field' => 'location',
           'value' => '%as%',
           'condition_type' => 'like'
         ]
    1 => [
      'filters' => [
         0 => [
           'field' => 'distance',
           'value' => '100',
           'condition_type' => 'lt'
         ]
      ]
    ]
  ]

Is it possible to just implemented it like this:

public function __construct(
 /Namespace/Module/Model/CollectionFactory $collection
){
 $this->collection = $collection;
}

public function execute(){
 $searchCriteria = $this->getRequest()->getPostValue('searchCriteria');
 $collections = $this->collection->create()->getList($searchCriteria);
 return $collections;
}
0

I think this is one of possible way to implement searchCriteria.

    $requestParams = $this->_request->getParams();
    foreach($requestParams as $key => $value){
        if($key == "location"){
            $filters[] = $this->_filterBuilder->setField($key)->setConditionType("like")->setValue($value)->create();    
        }
        elseif($key == "distance"){
            $filters[] = $this->_filterBuilder->setField($key)->setConditionType("lt")->setValue($value)->create(); 
        }
    }

    if(count($filters) > 0){


        foreach($filters as $filterData){
            $filterGroup[] =  $this->_filterGroupBuilder->addFilter($filterData)->create();
        }          

        $searchCriteria = $this->searchCriteriaBuilder->setFilterGroups($filterGroup)->create();
        $collections = $this->collection->create()->getList($searchCriteria);
        return $collections;
    }

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.