Magento – How to add %like% search functionality in header search Magento 2

magento-2.0magento2

When i search "cocacola" product it search 1 product which is "cocacola" but when i search "cola" then no product found. i want search "cola" and it should a product but right now no product found. i want use %like% condition.
I Want to add this functionality in header Search.

View Example

In Magento 1 Search work like https://app.hyfy.io/v/abfCoSnOT5n/
In Mahento 2 Search work like https://app.hyfy.io/v/ab3EtzbNT5n/

So Magento 2 Search Not Working Like Magento 1.

Best Answer

source : https://alanstorm.com/magento_2_understanding_object_repositories/

I think you are looking for something like this :

Verbose way :

//create our filter
$filter = $this->objectManager->create('Magento\Framework\Api\Filter');
$filter->setData('field','name');
$filter->setData('value','%coca%');
$filter->setData('condition_type','like');

//add our filter(s) to a group
$filter_group = $this->objectManager->create('Magento\Framework\Api\Search\FilterGroup');
$filter_group->setData('filters', [$filter]);

//add the group(s) to the search criteria object
$search_criteria = $this->objectManager->create('Magento\Framework\Api\SearchCriteriaInterface');
$search_criteria->setFilterGroups([$filter_group]);

//query the repository for the object(s)
$repo = $this->objectManager->get('Magento\Catalog\Model\ProductRepository');                        
$result = $repo->getList($search_criteria);
$products = $result->getItems();
foreach($products as $product)
{
    echo $product->getSku(),"\n";
}

Less verbose :

//create our filter
$filter = $this->objectManager
->create('Magento\Framework\Api\FilterBuilder')
->setField('name')
->setConditionType('like')
->setValue('%coca%')
->create();

//add our filter(s) to a group
$filter_group = $this->objectManager
->create('Magento\Framework\Api\Search\FilterGroupBuilder')
->addFilter($filter)
->create();
// $filter_group->setData('filters', [$filter]);

//add the group(s) to the search criteria object
$search_criteria = $this->objectManager
->create('Magento\Framework\Api\SearchCriteriaBuilder')
->setFilterGroups([$filter_group])
->create();

You can find all the condition type here : vendor/magento/framework/Api/CriteriaInterface.php

Related Topic