Magento 2 – Filter Product Collection with Custom Text Like Catalog Search

catalogsearchmagento2

I am just trying to filter product collection same like catalog search module, but not couldn't get the succeed with this. For this I tried this,

use Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection as SearchColletion;

$collection = $this->searchCollection->addSearchFilter('MY CUSTOM TEXT');

For this I checked vendor\magento\module-catalog-search\Model\ResourceModel\Fulltext\Collection.php to Investigate how it actual works in Magento catalog search, and found that in _renderFiltersBefore() Magento is using filterBuilder, searchCriteriaBuilder and so many things for searching, but couldn't understand properly.

Can someone put some light on this to get the actual result?

Best Answer

Okay, let me tell you the long story short.

First of all the method you referred addSearchFilter has to be deprecated and not recommended to be used. Because all it does is modifies initial search term specified by user. So, its responsibility does not correspond to the logic it provides. There are another eligible extension point. For example PreprocessorInterface which we use to update initial SearchTerm and grab synonyms and extend initial search phrase after that.

But if you would like to add additional Search Filter for the Full Text collection you have a recommended APIs for this:

Use addFieldToFilter method which accepts two parameters: field to which you would like to apply filtering and condition - value of the filter.

Filter field you are referring in this method should be "searchable" attribute.

Related Topic