Quick little snippet for reusing the Magento 2 advanced search programmatically.
The gist of functionality lies on injecting and using \Magento\Eav\Model\Config $eavConfig
and \Magento\CatalogSearch\Model\Advanced $catalogSearchAdvanced
, as shown in the following example.
<?php
namespace FoggylineSearchControllerSearch;
class Test extends \Foggyline\Search\Controller\Search
{
private $eavConfig;
protected $catalogSearchAdvanced;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Eav\Model\Config $eavConfig,
\Magento\CatalogSearch\Model\Advanced $catalogSearchAdvanced)
{
$this->eavConfig = $eavConfig;
$this->catalogSearchAdvanced = $catalogSearchAdvanced;
parent::__construct($context);
}
public function execute()
{
$queryValue = [];
// Assuming we are searching for existing "Rose Gold" labeled color
$queryValue['color'][] = $this->eavConfig
->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'color')
->getSource()
->getOptionId('Rose Gold');
// Assuming we are searching for "XL" labeled size
$queryValue['size'][] = $this->eavConfig
->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'size')
->getSource()
->getOptionId('XL');
$products = $this->catalogSearchAdvanced
->addFilters($queryValue)
->getProductCollection()
->setCurPage(1)
->setPageSize(9);
foreach ($products as $product) {
// $product->getName();
}
}
}
The $queryValue
has a certain structure. We could easily temporarily edit the vendor/magento/module-catalog-search/Controller/Advanced/Result.php
file by placing the var_dump
on the $this->getRequest()->getQueryValue()
expression when submitting the Advanced Search form from storefront page on /catalogsearch/advanced/
URL in order to observe that structure.