Magento 2 Layered Navigation on Advanced Search Result Page
I am able to enable 'Layered Navigation' on Catalog Search Result-Page "http://127.0.0.1/catalogsearch/result/index/" (see image below) by just enabling the storefront properties 'Use in Search Results Layered Navigation' of my two attributes.
How can I enable same 'Layered Navigation' also on Catalog Search ADVANCED Result-Page "http://127.0.0.1/catalogsearch/advanced/result/" ?
ps: I have tried the solution from "Magento 2 Layered Navigation in Advance Search Result" but it gives me an error:
- My Catalog Search ADVANCED Result-Page looks now (after trying above solution) like this:
As you can see the layered navigation price-filter shows all items from inventory, instead of just the 4 items that were found as result (see arrows).
- When I click on a price-filter option like '€0.00 - €999.99 (5)', Magento displays an error:
magento2 magento-2.1 layered-navigation catalogsearch search-result
bumped to the homepage by Community♦ 6 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
I am able to enable 'Layered Navigation' on Catalog Search Result-Page "http://127.0.0.1/catalogsearch/result/index/" (see image below) by just enabling the storefront properties 'Use in Search Results Layered Navigation' of my two attributes.
How can I enable same 'Layered Navigation' also on Catalog Search ADVANCED Result-Page "http://127.0.0.1/catalogsearch/advanced/result/" ?
ps: I have tried the solution from "Magento 2 Layered Navigation in Advance Search Result" but it gives me an error:
- My Catalog Search ADVANCED Result-Page looks now (after trying above solution) like this:
As you can see the layered navigation price-filter shows all items from inventory, instead of just the 4 items that were found as result (see arrows).
- When I click on a price-filter option like '€0.00 - €999.99 (5)', Magento displays an error:
magento2 magento-2.1 layered-navigation catalogsearch search-result
bumped to the homepage by Community♦ 6 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
I am able to enable 'Layered Navigation' on Catalog Search Result-Page "http://127.0.0.1/catalogsearch/result/index/" (see image below) by just enabling the storefront properties 'Use in Search Results Layered Navigation' of my two attributes.
How can I enable same 'Layered Navigation' also on Catalog Search ADVANCED Result-Page "http://127.0.0.1/catalogsearch/advanced/result/" ?
ps: I have tried the solution from "Magento 2 Layered Navigation in Advance Search Result" but it gives me an error:
- My Catalog Search ADVANCED Result-Page looks now (after trying above solution) like this:
As you can see the layered navigation price-filter shows all items from inventory, instead of just the 4 items that were found as result (see arrows).
- When I click on a price-filter option like '€0.00 - €999.99 (5)', Magento displays an error:
magento2 magento-2.1 layered-navigation catalogsearch search-result
I am able to enable 'Layered Navigation' on Catalog Search Result-Page "http://127.0.0.1/catalogsearch/result/index/" (see image below) by just enabling the storefront properties 'Use in Search Results Layered Navigation' of my two attributes.
How can I enable same 'Layered Navigation' also on Catalog Search ADVANCED Result-Page "http://127.0.0.1/catalogsearch/advanced/result/" ?
ps: I have tried the solution from "Magento 2 Layered Navigation in Advance Search Result" but it gives me an error:
- My Catalog Search ADVANCED Result-Page looks now (after trying above solution) like this:
As you can see the layered navigation price-filter shows all items from inventory, instead of just the 4 items that were found as result (see arrows).
- When I click on a price-filter option like '€0.00 - €999.99 (5)', Magento displays an error:
magento2 magento-2.1 layered-navigation catalogsearch search-result
magento2 magento-2.1 layered-navigation catalogsearch search-result
asked Aug 31 '17 at 15:12
shahir hajirshahir hajir
4461929
4461929
bumped to the homepage by Community♦ 6 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
bumped to the homepage by Community♦ 6 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
When ever your try to filter product based on price using advanced search form this sent header value like
http://mage26.net/catalogsearch/advanced/result/?name=&sku=&description=&short_description=&price%5Bfrom%5D=1&price%5Bto%5D=10
Price value goes to array form like from
and to
.
But, if you try to filter layered navigation its goes to string not a array like from
and to
http://mage26.net/catalogsearch/advanced/result/?description=&name=&price=-10000&short_description=&sku=
-10000
means price 0-10000
10000-
means price 10000- above
.
I tried Below Solution its works fine.
Override this Model Class: vendor/magento/module-catalog-search/Model/Advanced.php
.
Create di.xml file with in directory app/code/Vendor/Module/etc/di.xml
.
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogSearchModelAdvanced" type="CloridaAddFilterModelRewriteAdvanced" />
</config>
Then Create Advanced.php in with in app/code/Vendor/Module/Model/Rewrite/Advanced.php
Advanced.php
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleModelRewrite;
use MagentoCatalogModelConfig;
use MagentoCatalogModelProductVisibility;
use MagentoCatalogModelProductFactory;
use MagentoCatalogModelResourceModelEavAttribute;
use MagentoCatalogModelResourceModelProductAttributeCollectionFactory as AttributeCollectionFactory;
use MagentoCatalogModelResourceModelProductCollectionFactory as ProductCollectionFactory;
use MagentoCatalogSearchModelResourceModelAdvancedCollection as ProductCollection;
use MagentoCatalogSearchModelResourceModelAdvancedFactory;
use MagentoDirectoryModelCurrencyFactory;
use MagentoEavModelEntityAttribute as EntityAttribute;
use MagentoFrameworkModelContext;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkRegistry;
use MagentoStoreModelStoreManagerInterface;
/**
* Catalog advanced search model
* @method MagentoCatalogSearchModelResourceModelAdvanced getResource()
* @method int getEntityTypeId()
* @method MagentoCatalogSearchModelAdvanced setEntityTypeId(int $value)
* @method int getAttributeSetId()
* @method MagentoCatalogSearchModelAdvanced setAttributeSetId(int $value)
* @method string getTypeId()
* @method MagentoCatalogSearchModelAdvanced setTypeId(string $value)
* @method string getSku()
* @method MagentoCatalogSearchModelAdvanced setSku(string $value)
* @method int getHasOptions()
* @method MagentoCatalogSearchModelAdvanced setHasOptions(int $value)
* @method int getRequiredOptions()
* @method MagentoCatalogSearchModelAdvanced setRequiredOptions(int $value)
* @method string getCreatedAt()
* @method MagentoCatalogSearchModelAdvanced setCreatedAt(string $value)
* @method string getUpdatedAt()
* @method MagentoCatalogSearchModelAdvanced setUpdatedAt(string $value)
*
* @author Magento Core Team <core@magentocommerce.com>
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Advanced extends MagentoCatalogSearchModelAdvanced
{
/**
* User friendly search criteria list
*
* @var array
*/
protected $_searchCriterias = ;
/**
* Product collection
*
* @var ProductCollection
*/
protected $_productCollection;
/**
* Initialize dependencies
*
* @var Config
*/
protected $_catalogConfig;
/**
* Catalog product visibility
*
* @var Visibility
*/
protected $_catalogProductVisibility;
/**
* Attribute collection factory
*
* @var AttributeCollectionFactory
*/
protected $_attributeCollectionFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* Product factory
*
* @var ProductFactory
*/
protected $_productFactory;
/**
* Currency factory
*
* @var CurrencyFactory
*/
protected $_currencyFactory;
/**
* Advanced Collection Factory
*
* @var ProductCollectionFactory
*/
protected $productCollectionFactory;
protected $logger;
/**
* Construct
*
* @param Context $context
* @param Registry $registry
* @param AttributeCollectionFactory $attributeCollectionFactory
* @param Visibility $catalogProductVisibility
* @param Config $catalogConfig
* @param CurrencyFactory $currencyFactory
* @param ProductFactory $productFactory
* @param StoreManagerInterface $storeManager
* @param ProductCollectionFactory $productCollectionFactory
* @param AdvancedFactory $advancedFactory
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
Context $context,
Registry $registry,
AttributeCollectionFactory $attributeCollectionFactory,
Visibility $catalogProductVisibility,
Config $catalogConfig,
CurrencyFactory $currencyFactory,
ProductFactory $productFactory,
StoreManagerInterface $storeManager,
ProductCollectionFactory $productCollectionFactory,
AdvancedFactory $advancedFactory,
PsrLogLoggerInterface $loggerinterface,
array $data =
) {
$this->_attributeCollectionFactory = $attributeCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
$this->_catalogConfig = $catalogConfig;
$this->_currencyFactory = $currencyFactory;
$this->_productFactory = $productFactory;
$this->_storeManager = $storeManager;
$this->productCollectionFactory = $productCollectionFactory;
$this->logger = $loggerinterface;
parent::__construct(
$context,
$registry,
$attributeCollectionFactory,
$catalogProductVisibility,
$catalogConfig,
$currencyFactory,
$productFactory,
$storeManager,
$productCollectionFactory,
$advancedFactory,
$data
);
}
/**
* Add advanced search filters to product collection
*
* @param array $values
* @return $this
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function addFilters($values)
{
$attributes = $this->getAttributes();
$allConditions = ;
foreach ($attributes as $attribute) {
/* @var $attribute Attribute */
if (!isset($values[$attribute->getAttributeCode()])) {
continue;
}
$value = $values[$attribute->getAttributeCode()];
$preparedSearchValue = $this->getPreparedSearchCriteria($attribute, $value);
if (false === $preparedSearchValue) {
continue;
}
$this->addSearchCriteria($attribute, $preparedSearchValue);
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
if ($attribute->getBackendType() == 'datetime') {
$value['from'] = (isset($value['from']) && !empty($value['from']))
? date('Y-m-dTH:i:sZ', strtotime($value['from']))
: '';
$value['to'] = (isset($value['to']) && !empty($value['to']))
? date('Y-m-dTH:i:sZ', strtotime($value['to']))
: '';
}
$condition = $this->_getResource()->prepareCondition(
$attribute,
$value,
$this->getProductCollection()
);
if ($condition === false) {
continue;
}
$table = $attribute->getBackend()->getTable();
if ($attribute->getBackendType() == 'static') {
$attributeId = $attribute->getAttributeCode();
} else {
$attributeId = $attribute->getId();
}
$allConditions[$table][$attributeId] = $condition;
}
if ($allConditions) {
$this->_registry->register('advanced_search_conditions', $allConditions);
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else {
throw new LocalizedException(__('Please specify at least one search term.'));
}
return $this;
}
/**
* Retrieve array of attributes used in advanced search
*
* @return array|MagentoCatalogModelResourceModelProductAttributeCollection
*/
public function getAttributes()
{
$attributes = $this->getData('attributes');
if ($attributes === null) {
$product = $this->_productFactory->create();
$attributes = $this->_attributeCollectionFactory
->create()
->addHasOptionsFilter()
->addDisplayInAdvancedSearchFilter()
->addStoreLabel($this->_storeManager->getStore()->getId())
->setOrder('main_table.attribute_id', 'asc')
->load();
foreach ($attributes as $attribute) {
$attribute->setEntity($product->getResource());
}
$this->setData('attributes', $attributes);
}
return $attributes;
}
/**
* Retrieve advanced search product collection
*
* @return Collection
*/
public function getProductCollection()
{
if ($this->_productCollection === null) {
$collection = $this->productCollectionFactory->create();
$this->prepareProductCollection($collection);
if (!$collection) {
return $collection;
}
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
/**
* Prepare product collection
*
* @param Collection $collection
* @return $this
*/
public function prepareProductCollection($collection)
{
$collection
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->setStore($this->_storeManager->getStore())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter()
->setVisibility($this->_catalogProductVisibility->getVisibleInSearchIds());
return $this;
}
/**
* @param EntityAttribute $attribute
* @param mixed $value
* @return void
*/
protected function addSearchCriteria($attribute, $value)
{
if (!empty($value)) {
$this->_searchCriterias = ['name' => $attribute->getStoreLabel(), 'value' => $value];
}
}
/**
* Add data about search criteria to object state
*
* @todo: Move this code to block
*
* @param EntityAttribute $attribute
* @param mixed $value
* @return string|bool
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function getPreparedSearchCriteria($attribute, $value)
{
if (is_array($value)) {
if (isset($value['from']) && isset($value['to'])) {
if (!empty($value['from']) || !empty($value['to'])) {
if (isset($value['currency'])) {
/** @var $currencyModel Currency */
$currencyModel = $this->_currencyFactory->create()->load($value['currency']);
$from = $currencyModel->format($value['from'], , false);
$to = $currencyModel->format($value['to'], , false);
} else {
$currencyModel = null;
}
if (strlen($value['from']) > 0 && strlen($value['to']) > 0) {
// -
$value = sprintf(
'%s - %s',
$currencyModel ? $from : $value['from'],
$currencyModel ? $to : $value['to']
);
} elseif (strlen($value['from']) > 0) {
// and more
$value = __('%1 and greater', $currencyModel ? $from : $value['from']);
} elseif (strlen($value['to']) > 0) {
// to
$value = __('up to %1', $currencyModel ? $to : $value['to']);
}
} else {
return '';
}
}
}
if (($attribute->getFrontendInput() == 'select' ||
$attribute->getFrontendInput() == 'multiselect') && is_array($value)
) {
foreach ($value as $key => $val) {
$value[$key] = $attribute->getSource()->getOptionText($val);
if (is_array($value[$key])) {
$value[$key] = $value[$key]['label'];
}
}
$value = implode(', ', $value);
} elseif ($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') {
$value = $attribute->getSource()->getOptionText($value);
if (is_array($value)) {
$value = $value['label'];
}
} elseif ($attribute->getFrontendInput() == 'boolean') {
$value = $value == 1
? __('Yes')
: __('No');
}
return $value;
}
/**
* Returns prepared search criterias in text
*
* @return array
*/
public function getSearchCriterias()
{
return $this->_searchCriterias;
}
}
With in the Price Section, I have change like this.
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
Then, Clear cache and Check it let me know if you have issue.
1
How to add Layered navigation on Custom Product Collection? I am displaying products by brand using custom controller.
– Magecode
Sep 1 '17 at 4:53
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f191471%2fmagento-2-layered-navigation-on-advanced-search-result-page%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
When ever your try to filter product based on price using advanced search form this sent header value like
http://mage26.net/catalogsearch/advanced/result/?name=&sku=&description=&short_description=&price%5Bfrom%5D=1&price%5Bto%5D=10
Price value goes to array form like from
and to
.
But, if you try to filter layered navigation its goes to string not a array like from
and to
http://mage26.net/catalogsearch/advanced/result/?description=&name=&price=-10000&short_description=&sku=
-10000
means price 0-10000
10000-
means price 10000- above
.
I tried Below Solution its works fine.
Override this Model Class: vendor/magento/module-catalog-search/Model/Advanced.php
.
Create di.xml file with in directory app/code/Vendor/Module/etc/di.xml
.
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogSearchModelAdvanced" type="CloridaAddFilterModelRewriteAdvanced" />
</config>
Then Create Advanced.php in with in app/code/Vendor/Module/Model/Rewrite/Advanced.php
Advanced.php
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleModelRewrite;
use MagentoCatalogModelConfig;
use MagentoCatalogModelProductVisibility;
use MagentoCatalogModelProductFactory;
use MagentoCatalogModelResourceModelEavAttribute;
use MagentoCatalogModelResourceModelProductAttributeCollectionFactory as AttributeCollectionFactory;
use MagentoCatalogModelResourceModelProductCollectionFactory as ProductCollectionFactory;
use MagentoCatalogSearchModelResourceModelAdvancedCollection as ProductCollection;
use MagentoCatalogSearchModelResourceModelAdvancedFactory;
use MagentoDirectoryModelCurrencyFactory;
use MagentoEavModelEntityAttribute as EntityAttribute;
use MagentoFrameworkModelContext;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkRegistry;
use MagentoStoreModelStoreManagerInterface;
/**
* Catalog advanced search model
* @method MagentoCatalogSearchModelResourceModelAdvanced getResource()
* @method int getEntityTypeId()
* @method MagentoCatalogSearchModelAdvanced setEntityTypeId(int $value)
* @method int getAttributeSetId()
* @method MagentoCatalogSearchModelAdvanced setAttributeSetId(int $value)
* @method string getTypeId()
* @method MagentoCatalogSearchModelAdvanced setTypeId(string $value)
* @method string getSku()
* @method MagentoCatalogSearchModelAdvanced setSku(string $value)
* @method int getHasOptions()
* @method MagentoCatalogSearchModelAdvanced setHasOptions(int $value)
* @method int getRequiredOptions()
* @method MagentoCatalogSearchModelAdvanced setRequiredOptions(int $value)
* @method string getCreatedAt()
* @method MagentoCatalogSearchModelAdvanced setCreatedAt(string $value)
* @method string getUpdatedAt()
* @method MagentoCatalogSearchModelAdvanced setUpdatedAt(string $value)
*
* @author Magento Core Team <core@magentocommerce.com>
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Advanced extends MagentoCatalogSearchModelAdvanced
{
/**
* User friendly search criteria list
*
* @var array
*/
protected $_searchCriterias = ;
/**
* Product collection
*
* @var ProductCollection
*/
protected $_productCollection;
/**
* Initialize dependencies
*
* @var Config
*/
protected $_catalogConfig;
/**
* Catalog product visibility
*
* @var Visibility
*/
protected $_catalogProductVisibility;
/**
* Attribute collection factory
*
* @var AttributeCollectionFactory
*/
protected $_attributeCollectionFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* Product factory
*
* @var ProductFactory
*/
protected $_productFactory;
/**
* Currency factory
*
* @var CurrencyFactory
*/
protected $_currencyFactory;
/**
* Advanced Collection Factory
*
* @var ProductCollectionFactory
*/
protected $productCollectionFactory;
protected $logger;
/**
* Construct
*
* @param Context $context
* @param Registry $registry
* @param AttributeCollectionFactory $attributeCollectionFactory
* @param Visibility $catalogProductVisibility
* @param Config $catalogConfig
* @param CurrencyFactory $currencyFactory
* @param ProductFactory $productFactory
* @param StoreManagerInterface $storeManager
* @param ProductCollectionFactory $productCollectionFactory
* @param AdvancedFactory $advancedFactory
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
Context $context,
Registry $registry,
AttributeCollectionFactory $attributeCollectionFactory,
Visibility $catalogProductVisibility,
Config $catalogConfig,
CurrencyFactory $currencyFactory,
ProductFactory $productFactory,
StoreManagerInterface $storeManager,
ProductCollectionFactory $productCollectionFactory,
AdvancedFactory $advancedFactory,
PsrLogLoggerInterface $loggerinterface,
array $data =
) {
$this->_attributeCollectionFactory = $attributeCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
$this->_catalogConfig = $catalogConfig;
$this->_currencyFactory = $currencyFactory;
$this->_productFactory = $productFactory;
$this->_storeManager = $storeManager;
$this->productCollectionFactory = $productCollectionFactory;
$this->logger = $loggerinterface;
parent::__construct(
$context,
$registry,
$attributeCollectionFactory,
$catalogProductVisibility,
$catalogConfig,
$currencyFactory,
$productFactory,
$storeManager,
$productCollectionFactory,
$advancedFactory,
$data
);
}
/**
* Add advanced search filters to product collection
*
* @param array $values
* @return $this
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function addFilters($values)
{
$attributes = $this->getAttributes();
$allConditions = ;
foreach ($attributes as $attribute) {
/* @var $attribute Attribute */
if (!isset($values[$attribute->getAttributeCode()])) {
continue;
}
$value = $values[$attribute->getAttributeCode()];
$preparedSearchValue = $this->getPreparedSearchCriteria($attribute, $value);
if (false === $preparedSearchValue) {
continue;
}
$this->addSearchCriteria($attribute, $preparedSearchValue);
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
if ($attribute->getBackendType() == 'datetime') {
$value['from'] = (isset($value['from']) && !empty($value['from']))
? date('Y-m-dTH:i:sZ', strtotime($value['from']))
: '';
$value['to'] = (isset($value['to']) && !empty($value['to']))
? date('Y-m-dTH:i:sZ', strtotime($value['to']))
: '';
}
$condition = $this->_getResource()->prepareCondition(
$attribute,
$value,
$this->getProductCollection()
);
if ($condition === false) {
continue;
}
$table = $attribute->getBackend()->getTable();
if ($attribute->getBackendType() == 'static') {
$attributeId = $attribute->getAttributeCode();
} else {
$attributeId = $attribute->getId();
}
$allConditions[$table][$attributeId] = $condition;
}
if ($allConditions) {
$this->_registry->register('advanced_search_conditions', $allConditions);
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else {
throw new LocalizedException(__('Please specify at least one search term.'));
}
return $this;
}
/**
* Retrieve array of attributes used in advanced search
*
* @return array|MagentoCatalogModelResourceModelProductAttributeCollection
*/
public function getAttributes()
{
$attributes = $this->getData('attributes');
if ($attributes === null) {
$product = $this->_productFactory->create();
$attributes = $this->_attributeCollectionFactory
->create()
->addHasOptionsFilter()
->addDisplayInAdvancedSearchFilter()
->addStoreLabel($this->_storeManager->getStore()->getId())
->setOrder('main_table.attribute_id', 'asc')
->load();
foreach ($attributes as $attribute) {
$attribute->setEntity($product->getResource());
}
$this->setData('attributes', $attributes);
}
return $attributes;
}
/**
* Retrieve advanced search product collection
*
* @return Collection
*/
public function getProductCollection()
{
if ($this->_productCollection === null) {
$collection = $this->productCollectionFactory->create();
$this->prepareProductCollection($collection);
if (!$collection) {
return $collection;
}
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
/**
* Prepare product collection
*
* @param Collection $collection
* @return $this
*/
public function prepareProductCollection($collection)
{
$collection
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->setStore($this->_storeManager->getStore())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter()
->setVisibility($this->_catalogProductVisibility->getVisibleInSearchIds());
return $this;
}
/**
* @param EntityAttribute $attribute
* @param mixed $value
* @return void
*/
protected function addSearchCriteria($attribute, $value)
{
if (!empty($value)) {
$this->_searchCriterias = ['name' => $attribute->getStoreLabel(), 'value' => $value];
}
}
/**
* Add data about search criteria to object state
*
* @todo: Move this code to block
*
* @param EntityAttribute $attribute
* @param mixed $value
* @return string|bool
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function getPreparedSearchCriteria($attribute, $value)
{
if (is_array($value)) {
if (isset($value['from']) && isset($value['to'])) {
if (!empty($value['from']) || !empty($value['to'])) {
if (isset($value['currency'])) {
/** @var $currencyModel Currency */
$currencyModel = $this->_currencyFactory->create()->load($value['currency']);
$from = $currencyModel->format($value['from'], , false);
$to = $currencyModel->format($value['to'], , false);
} else {
$currencyModel = null;
}
if (strlen($value['from']) > 0 && strlen($value['to']) > 0) {
// -
$value = sprintf(
'%s - %s',
$currencyModel ? $from : $value['from'],
$currencyModel ? $to : $value['to']
);
} elseif (strlen($value['from']) > 0) {
// and more
$value = __('%1 and greater', $currencyModel ? $from : $value['from']);
} elseif (strlen($value['to']) > 0) {
// to
$value = __('up to %1', $currencyModel ? $to : $value['to']);
}
} else {
return '';
}
}
}
if (($attribute->getFrontendInput() == 'select' ||
$attribute->getFrontendInput() == 'multiselect') && is_array($value)
) {
foreach ($value as $key => $val) {
$value[$key] = $attribute->getSource()->getOptionText($val);
if (is_array($value[$key])) {
$value[$key] = $value[$key]['label'];
}
}
$value = implode(', ', $value);
} elseif ($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') {
$value = $attribute->getSource()->getOptionText($value);
if (is_array($value)) {
$value = $value['label'];
}
} elseif ($attribute->getFrontendInput() == 'boolean') {
$value = $value == 1
? __('Yes')
: __('No');
}
return $value;
}
/**
* Returns prepared search criterias in text
*
* @return array
*/
public function getSearchCriterias()
{
return $this->_searchCriterias;
}
}
With in the Price Section, I have change like this.
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
Then, Clear cache and Check it let me know if you have issue.
1
How to add Layered navigation on Custom Product Collection? I am displaying products by brand using custom controller.
– Magecode
Sep 1 '17 at 4:53
add a comment |
When ever your try to filter product based on price using advanced search form this sent header value like
http://mage26.net/catalogsearch/advanced/result/?name=&sku=&description=&short_description=&price%5Bfrom%5D=1&price%5Bto%5D=10
Price value goes to array form like from
and to
.
But, if you try to filter layered navigation its goes to string not a array like from
and to
http://mage26.net/catalogsearch/advanced/result/?description=&name=&price=-10000&short_description=&sku=
-10000
means price 0-10000
10000-
means price 10000- above
.
I tried Below Solution its works fine.
Override this Model Class: vendor/magento/module-catalog-search/Model/Advanced.php
.
Create di.xml file with in directory app/code/Vendor/Module/etc/di.xml
.
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogSearchModelAdvanced" type="CloridaAddFilterModelRewriteAdvanced" />
</config>
Then Create Advanced.php in with in app/code/Vendor/Module/Model/Rewrite/Advanced.php
Advanced.php
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleModelRewrite;
use MagentoCatalogModelConfig;
use MagentoCatalogModelProductVisibility;
use MagentoCatalogModelProductFactory;
use MagentoCatalogModelResourceModelEavAttribute;
use MagentoCatalogModelResourceModelProductAttributeCollectionFactory as AttributeCollectionFactory;
use MagentoCatalogModelResourceModelProductCollectionFactory as ProductCollectionFactory;
use MagentoCatalogSearchModelResourceModelAdvancedCollection as ProductCollection;
use MagentoCatalogSearchModelResourceModelAdvancedFactory;
use MagentoDirectoryModelCurrencyFactory;
use MagentoEavModelEntityAttribute as EntityAttribute;
use MagentoFrameworkModelContext;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkRegistry;
use MagentoStoreModelStoreManagerInterface;
/**
* Catalog advanced search model
* @method MagentoCatalogSearchModelResourceModelAdvanced getResource()
* @method int getEntityTypeId()
* @method MagentoCatalogSearchModelAdvanced setEntityTypeId(int $value)
* @method int getAttributeSetId()
* @method MagentoCatalogSearchModelAdvanced setAttributeSetId(int $value)
* @method string getTypeId()
* @method MagentoCatalogSearchModelAdvanced setTypeId(string $value)
* @method string getSku()
* @method MagentoCatalogSearchModelAdvanced setSku(string $value)
* @method int getHasOptions()
* @method MagentoCatalogSearchModelAdvanced setHasOptions(int $value)
* @method int getRequiredOptions()
* @method MagentoCatalogSearchModelAdvanced setRequiredOptions(int $value)
* @method string getCreatedAt()
* @method MagentoCatalogSearchModelAdvanced setCreatedAt(string $value)
* @method string getUpdatedAt()
* @method MagentoCatalogSearchModelAdvanced setUpdatedAt(string $value)
*
* @author Magento Core Team <core@magentocommerce.com>
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Advanced extends MagentoCatalogSearchModelAdvanced
{
/**
* User friendly search criteria list
*
* @var array
*/
protected $_searchCriterias = ;
/**
* Product collection
*
* @var ProductCollection
*/
protected $_productCollection;
/**
* Initialize dependencies
*
* @var Config
*/
protected $_catalogConfig;
/**
* Catalog product visibility
*
* @var Visibility
*/
protected $_catalogProductVisibility;
/**
* Attribute collection factory
*
* @var AttributeCollectionFactory
*/
protected $_attributeCollectionFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* Product factory
*
* @var ProductFactory
*/
protected $_productFactory;
/**
* Currency factory
*
* @var CurrencyFactory
*/
protected $_currencyFactory;
/**
* Advanced Collection Factory
*
* @var ProductCollectionFactory
*/
protected $productCollectionFactory;
protected $logger;
/**
* Construct
*
* @param Context $context
* @param Registry $registry
* @param AttributeCollectionFactory $attributeCollectionFactory
* @param Visibility $catalogProductVisibility
* @param Config $catalogConfig
* @param CurrencyFactory $currencyFactory
* @param ProductFactory $productFactory
* @param StoreManagerInterface $storeManager
* @param ProductCollectionFactory $productCollectionFactory
* @param AdvancedFactory $advancedFactory
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
Context $context,
Registry $registry,
AttributeCollectionFactory $attributeCollectionFactory,
Visibility $catalogProductVisibility,
Config $catalogConfig,
CurrencyFactory $currencyFactory,
ProductFactory $productFactory,
StoreManagerInterface $storeManager,
ProductCollectionFactory $productCollectionFactory,
AdvancedFactory $advancedFactory,
PsrLogLoggerInterface $loggerinterface,
array $data =
) {
$this->_attributeCollectionFactory = $attributeCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
$this->_catalogConfig = $catalogConfig;
$this->_currencyFactory = $currencyFactory;
$this->_productFactory = $productFactory;
$this->_storeManager = $storeManager;
$this->productCollectionFactory = $productCollectionFactory;
$this->logger = $loggerinterface;
parent::__construct(
$context,
$registry,
$attributeCollectionFactory,
$catalogProductVisibility,
$catalogConfig,
$currencyFactory,
$productFactory,
$storeManager,
$productCollectionFactory,
$advancedFactory,
$data
);
}
/**
* Add advanced search filters to product collection
*
* @param array $values
* @return $this
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function addFilters($values)
{
$attributes = $this->getAttributes();
$allConditions = ;
foreach ($attributes as $attribute) {
/* @var $attribute Attribute */
if (!isset($values[$attribute->getAttributeCode()])) {
continue;
}
$value = $values[$attribute->getAttributeCode()];
$preparedSearchValue = $this->getPreparedSearchCriteria($attribute, $value);
if (false === $preparedSearchValue) {
continue;
}
$this->addSearchCriteria($attribute, $preparedSearchValue);
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
if ($attribute->getBackendType() == 'datetime') {
$value['from'] = (isset($value['from']) && !empty($value['from']))
? date('Y-m-dTH:i:sZ', strtotime($value['from']))
: '';
$value['to'] = (isset($value['to']) && !empty($value['to']))
? date('Y-m-dTH:i:sZ', strtotime($value['to']))
: '';
}
$condition = $this->_getResource()->prepareCondition(
$attribute,
$value,
$this->getProductCollection()
);
if ($condition === false) {
continue;
}
$table = $attribute->getBackend()->getTable();
if ($attribute->getBackendType() == 'static') {
$attributeId = $attribute->getAttributeCode();
} else {
$attributeId = $attribute->getId();
}
$allConditions[$table][$attributeId] = $condition;
}
if ($allConditions) {
$this->_registry->register('advanced_search_conditions', $allConditions);
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else {
throw new LocalizedException(__('Please specify at least one search term.'));
}
return $this;
}
/**
* Retrieve array of attributes used in advanced search
*
* @return array|MagentoCatalogModelResourceModelProductAttributeCollection
*/
public function getAttributes()
{
$attributes = $this->getData('attributes');
if ($attributes === null) {
$product = $this->_productFactory->create();
$attributes = $this->_attributeCollectionFactory
->create()
->addHasOptionsFilter()
->addDisplayInAdvancedSearchFilter()
->addStoreLabel($this->_storeManager->getStore()->getId())
->setOrder('main_table.attribute_id', 'asc')
->load();
foreach ($attributes as $attribute) {
$attribute->setEntity($product->getResource());
}
$this->setData('attributes', $attributes);
}
return $attributes;
}
/**
* Retrieve advanced search product collection
*
* @return Collection
*/
public function getProductCollection()
{
if ($this->_productCollection === null) {
$collection = $this->productCollectionFactory->create();
$this->prepareProductCollection($collection);
if (!$collection) {
return $collection;
}
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
/**
* Prepare product collection
*
* @param Collection $collection
* @return $this
*/
public function prepareProductCollection($collection)
{
$collection
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->setStore($this->_storeManager->getStore())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter()
->setVisibility($this->_catalogProductVisibility->getVisibleInSearchIds());
return $this;
}
/**
* @param EntityAttribute $attribute
* @param mixed $value
* @return void
*/
protected function addSearchCriteria($attribute, $value)
{
if (!empty($value)) {
$this->_searchCriterias = ['name' => $attribute->getStoreLabel(), 'value' => $value];
}
}
/**
* Add data about search criteria to object state
*
* @todo: Move this code to block
*
* @param EntityAttribute $attribute
* @param mixed $value
* @return string|bool
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function getPreparedSearchCriteria($attribute, $value)
{
if (is_array($value)) {
if (isset($value['from']) && isset($value['to'])) {
if (!empty($value['from']) || !empty($value['to'])) {
if (isset($value['currency'])) {
/** @var $currencyModel Currency */
$currencyModel = $this->_currencyFactory->create()->load($value['currency']);
$from = $currencyModel->format($value['from'], , false);
$to = $currencyModel->format($value['to'], , false);
} else {
$currencyModel = null;
}
if (strlen($value['from']) > 0 && strlen($value['to']) > 0) {
// -
$value = sprintf(
'%s - %s',
$currencyModel ? $from : $value['from'],
$currencyModel ? $to : $value['to']
);
} elseif (strlen($value['from']) > 0) {
// and more
$value = __('%1 and greater', $currencyModel ? $from : $value['from']);
} elseif (strlen($value['to']) > 0) {
// to
$value = __('up to %1', $currencyModel ? $to : $value['to']);
}
} else {
return '';
}
}
}
if (($attribute->getFrontendInput() == 'select' ||
$attribute->getFrontendInput() == 'multiselect') && is_array($value)
) {
foreach ($value as $key => $val) {
$value[$key] = $attribute->getSource()->getOptionText($val);
if (is_array($value[$key])) {
$value[$key] = $value[$key]['label'];
}
}
$value = implode(', ', $value);
} elseif ($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') {
$value = $attribute->getSource()->getOptionText($value);
if (is_array($value)) {
$value = $value['label'];
}
} elseif ($attribute->getFrontendInput() == 'boolean') {
$value = $value == 1
? __('Yes')
: __('No');
}
return $value;
}
/**
* Returns prepared search criterias in text
*
* @return array
*/
public function getSearchCriterias()
{
return $this->_searchCriterias;
}
}
With in the Price Section, I have change like this.
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
Then, Clear cache and Check it let me know if you have issue.
1
How to add Layered navigation on Custom Product Collection? I am displaying products by brand using custom controller.
– Magecode
Sep 1 '17 at 4:53
add a comment |
When ever your try to filter product based on price using advanced search form this sent header value like
http://mage26.net/catalogsearch/advanced/result/?name=&sku=&description=&short_description=&price%5Bfrom%5D=1&price%5Bto%5D=10
Price value goes to array form like from
and to
.
But, if you try to filter layered navigation its goes to string not a array like from
and to
http://mage26.net/catalogsearch/advanced/result/?description=&name=&price=-10000&short_description=&sku=
-10000
means price 0-10000
10000-
means price 10000- above
.
I tried Below Solution its works fine.
Override this Model Class: vendor/magento/module-catalog-search/Model/Advanced.php
.
Create di.xml file with in directory app/code/Vendor/Module/etc/di.xml
.
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogSearchModelAdvanced" type="CloridaAddFilterModelRewriteAdvanced" />
</config>
Then Create Advanced.php in with in app/code/Vendor/Module/Model/Rewrite/Advanced.php
Advanced.php
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleModelRewrite;
use MagentoCatalogModelConfig;
use MagentoCatalogModelProductVisibility;
use MagentoCatalogModelProductFactory;
use MagentoCatalogModelResourceModelEavAttribute;
use MagentoCatalogModelResourceModelProductAttributeCollectionFactory as AttributeCollectionFactory;
use MagentoCatalogModelResourceModelProductCollectionFactory as ProductCollectionFactory;
use MagentoCatalogSearchModelResourceModelAdvancedCollection as ProductCollection;
use MagentoCatalogSearchModelResourceModelAdvancedFactory;
use MagentoDirectoryModelCurrencyFactory;
use MagentoEavModelEntityAttribute as EntityAttribute;
use MagentoFrameworkModelContext;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkRegistry;
use MagentoStoreModelStoreManagerInterface;
/**
* Catalog advanced search model
* @method MagentoCatalogSearchModelResourceModelAdvanced getResource()
* @method int getEntityTypeId()
* @method MagentoCatalogSearchModelAdvanced setEntityTypeId(int $value)
* @method int getAttributeSetId()
* @method MagentoCatalogSearchModelAdvanced setAttributeSetId(int $value)
* @method string getTypeId()
* @method MagentoCatalogSearchModelAdvanced setTypeId(string $value)
* @method string getSku()
* @method MagentoCatalogSearchModelAdvanced setSku(string $value)
* @method int getHasOptions()
* @method MagentoCatalogSearchModelAdvanced setHasOptions(int $value)
* @method int getRequiredOptions()
* @method MagentoCatalogSearchModelAdvanced setRequiredOptions(int $value)
* @method string getCreatedAt()
* @method MagentoCatalogSearchModelAdvanced setCreatedAt(string $value)
* @method string getUpdatedAt()
* @method MagentoCatalogSearchModelAdvanced setUpdatedAt(string $value)
*
* @author Magento Core Team <core@magentocommerce.com>
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Advanced extends MagentoCatalogSearchModelAdvanced
{
/**
* User friendly search criteria list
*
* @var array
*/
protected $_searchCriterias = ;
/**
* Product collection
*
* @var ProductCollection
*/
protected $_productCollection;
/**
* Initialize dependencies
*
* @var Config
*/
protected $_catalogConfig;
/**
* Catalog product visibility
*
* @var Visibility
*/
protected $_catalogProductVisibility;
/**
* Attribute collection factory
*
* @var AttributeCollectionFactory
*/
protected $_attributeCollectionFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* Product factory
*
* @var ProductFactory
*/
protected $_productFactory;
/**
* Currency factory
*
* @var CurrencyFactory
*/
protected $_currencyFactory;
/**
* Advanced Collection Factory
*
* @var ProductCollectionFactory
*/
protected $productCollectionFactory;
protected $logger;
/**
* Construct
*
* @param Context $context
* @param Registry $registry
* @param AttributeCollectionFactory $attributeCollectionFactory
* @param Visibility $catalogProductVisibility
* @param Config $catalogConfig
* @param CurrencyFactory $currencyFactory
* @param ProductFactory $productFactory
* @param StoreManagerInterface $storeManager
* @param ProductCollectionFactory $productCollectionFactory
* @param AdvancedFactory $advancedFactory
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
Context $context,
Registry $registry,
AttributeCollectionFactory $attributeCollectionFactory,
Visibility $catalogProductVisibility,
Config $catalogConfig,
CurrencyFactory $currencyFactory,
ProductFactory $productFactory,
StoreManagerInterface $storeManager,
ProductCollectionFactory $productCollectionFactory,
AdvancedFactory $advancedFactory,
PsrLogLoggerInterface $loggerinterface,
array $data =
) {
$this->_attributeCollectionFactory = $attributeCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
$this->_catalogConfig = $catalogConfig;
$this->_currencyFactory = $currencyFactory;
$this->_productFactory = $productFactory;
$this->_storeManager = $storeManager;
$this->productCollectionFactory = $productCollectionFactory;
$this->logger = $loggerinterface;
parent::__construct(
$context,
$registry,
$attributeCollectionFactory,
$catalogProductVisibility,
$catalogConfig,
$currencyFactory,
$productFactory,
$storeManager,
$productCollectionFactory,
$advancedFactory,
$data
);
}
/**
* Add advanced search filters to product collection
*
* @param array $values
* @return $this
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function addFilters($values)
{
$attributes = $this->getAttributes();
$allConditions = ;
foreach ($attributes as $attribute) {
/* @var $attribute Attribute */
if (!isset($values[$attribute->getAttributeCode()])) {
continue;
}
$value = $values[$attribute->getAttributeCode()];
$preparedSearchValue = $this->getPreparedSearchCriteria($attribute, $value);
if (false === $preparedSearchValue) {
continue;
}
$this->addSearchCriteria($attribute, $preparedSearchValue);
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
if ($attribute->getBackendType() == 'datetime') {
$value['from'] = (isset($value['from']) && !empty($value['from']))
? date('Y-m-dTH:i:sZ', strtotime($value['from']))
: '';
$value['to'] = (isset($value['to']) && !empty($value['to']))
? date('Y-m-dTH:i:sZ', strtotime($value['to']))
: '';
}
$condition = $this->_getResource()->prepareCondition(
$attribute,
$value,
$this->getProductCollection()
);
if ($condition === false) {
continue;
}
$table = $attribute->getBackend()->getTable();
if ($attribute->getBackendType() == 'static') {
$attributeId = $attribute->getAttributeCode();
} else {
$attributeId = $attribute->getId();
}
$allConditions[$table][$attributeId] = $condition;
}
if ($allConditions) {
$this->_registry->register('advanced_search_conditions', $allConditions);
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else {
throw new LocalizedException(__('Please specify at least one search term.'));
}
return $this;
}
/**
* Retrieve array of attributes used in advanced search
*
* @return array|MagentoCatalogModelResourceModelProductAttributeCollection
*/
public function getAttributes()
{
$attributes = $this->getData('attributes');
if ($attributes === null) {
$product = $this->_productFactory->create();
$attributes = $this->_attributeCollectionFactory
->create()
->addHasOptionsFilter()
->addDisplayInAdvancedSearchFilter()
->addStoreLabel($this->_storeManager->getStore()->getId())
->setOrder('main_table.attribute_id', 'asc')
->load();
foreach ($attributes as $attribute) {
$attribute->setEntity($product->getResource());
}
$this->setData('attributes', $attributes);
}
return $attributes;
}
/**
* Retrieve advanced search product collection
*
* @return Collection
*/
public function getProductCollection()
{
if ($this->_productCollection === null) {
$collection = $this->productCollectionFactory->create();
$this->prepareProductCollection($collection);
if (!$collection) {
return $collection;
}
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
/**
* Prepare product collection
*
* @param Collection $collection
* @return $this
*/
public function prepareProductCollection($collection)
{
$collection
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->setStore($this->_storeManager->getStore())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter()
->setVisibility($this->_catalogProductVisibility->getVisibleInSearchIds());
return $this;
}
/**
* @param EntityAttribute $attribute
* @param mixed $value
* @return void
*/
protected function addSearchCriteria($attribute, $value)
{
if (!empty($value)) {
$this->_searchCriterias = ['name' => $attribute->getStoreLabel(), 'value' => $value];
}
}
/**
* Add data about search criteria to object state
*
* @todo: Move this code to block
*
* @param EntityAttribute $attribute
* @param mixed $value
* @return string|bool
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function getPreparedSearchCriteria($attribute, $value)
{
if (is_array($value)) {
if (isset($value['from']) && isset($value['to'])) {
if (!empty($value['from']) || !empty($value['to'])) {
if (isset($value['currency'])) {
/** @var $currencyModel Currency */
$currencyModel = $this->_currencyFactory->create()->load($value['currency']);
$from = $currencyModel->format($value['from'], , false);
$to = $currencyModel->format($value['to'], , false);
} else {
$currencyModel = null;
}
if (strlen($value['from']) > 0 && strlen($value['to']) > 0) {
// -
$value = sprintf(
'%s - %s',
$currencyModel ? $from : $value['from'],
$currencyModel ? $to : $value['to']
);
} elseif (strlen($value['from']) > 0) {
// and more
$value = __('%1 and greater', $currencyModel ? $from : $value['from']);
} elseif (strlen($value['to']) > 0) {
// to
$value = __('up to %1', $currencyModel ? $to : $value['to']);
}
} else {
return '';
}
}
}
if (($attribute->getFrontendInput() == 'select' ||
$attribute->getFrontendInput() == 'multiselect') && is_array($value)
) {
foreach ($value as $key => $val) {
$value[$key] = $attribute->getSource()->getOptionText($val);
if (is_array($value[$key])) {
$value[$key] = $value[$key]['label'];
}
}
$value = implode(', ', $value);
} elseif ($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') {
$value = $attribute->getSource()->getOptionText($value);
if (is_array($value)) {
$value = $value['label'];
}
} elseif ($attribute->getFrontendInput() == 'boolean') {
$value = $value == 1
? __('Yes')
: __('No');
}
return $value;
}
/**
* Returns prepared search criterias in text
*
* @return array
*/
public function getSearchCriterias()
{
return $this->_searchCriterias;
}
}
With in the Price Section, I have change like this.
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
Then, Clear cache and Check it let me know if you have issue.
When ever your try to filter product based on price using advanced search form this sent header value like
http://mage26.net/catalogsearch/advanced/result/?name=&sku=&description=&short_description=&price%5Bfrom%5D=1&price%5Bto%5D=10
Price value goes to array form like from
and to
.
But, if you try to filter layered navigation its goes to string not a array like from
and to
http://mage26.net/catalogsearch/advanced/result/?description=&name=&price=-10000&short_description=&sku=
-10000
means price 0-10000
10000-
means price 10000- above
.
I tried Below Solution its works fine.
Override this Model Class: vendor/magento/module-catalog-search/Model/Advanced.php
.
Create di.xml file with in directory app/code/Vendor/Module/etc/di.xml
.
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="MagentoCatalogSearchModelAdvanced" type="CloridaAddFilterModelRewriteAdvanced" />
</config>
Then Create Advanced.php in with in app/code/Vendor/Module/Model/Rewrite/Advanced.php
Advanced.php
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleModelRewrite;
use MagentoCatalogModelConfig;
use MagentoCatalogModelProductVisibility;
use MagentoCatalogModelProductFactory;
use MagentoCatalogModelResourceModelEavAttribute;
use MagentoCatalogModelResourceModelProductAttributeCollectionFactory as AttributeCollectionFactory;
use MagentoCatalogModelResourceModelProductCollectionFactory as ProductCollectionFactory;
use MagentoCatalogSearchModelResourceModelAdvancedCollection as ProductCollection;
use MagentoCatalogSearchModelResourceModelAdvancedFactory;
use MagentoDirectoryModelCurrencyFactory;
use MagentoEavModelEntityAttribute as EntityAttribute;
use MagentoFrameworkModelContext;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkRegistry;
use MagentoStoreModelStoreManagerInterface;
/**
* Catalog advanced search model
* @method MagentoCatalogSearchModelResourceModelAdvanced getResource()
* @method int getEntityTypeId()
* @method MagentoCatalogSearchModelAdvanced setEntityTypeId(int $value)
* @method int getAttributeSetId()
* @method MagentoCatalogSearchModelAdvanced setAttributeSetId(int $value)
* @method string getTypeId()
* @method MagentoCatalogSearchModelAdvanced setTypeId(string $value)
* @method string getSku()
* @method MagentoCatalogSearchModelAdvanced setSku(string $value)
* @method int getHasOptions()
* @method MagentoCatalogSearchModelAdvanced setHasOptions(int $value)
* @method int getRequiredOptions()
* @method MagentoCatalogSearchModelAdvanced setRequiredOptions(int $value)
* @method string getCreatedAt()
* @method MagentoCatalogSearchModelAdvanced setCreatedAt(string $value)
* @method string getUpdatedAt()
* @method MagentoCatalogSearchModelAdvanced setUpdatedAt(string $value)
*
* @author Magento Core Team <core@magentocommerce.com>
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Advanced extends MagentoCatalogSearchModelAdvanced
{
/**
* User friendly search criteria list
*
* @var array
*/
protected $_searchCriterias = ;
/**
* Product collection
*
* @var ProductCollection
*/
protected $_productCollection;
/**
* Initialize dependencies
*
* @var Config
*/
protected $_catalogConfig;
/**
* Catalog product visibility
*
* @var Visibility
*/
protected $_catalogProductVisibility;
/**
* Attribute collection factory
*
* @var AttributeCollectionFactory
*/
protected $_attributeCollectionFactory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* Product factory
*
* @var ProductFactory
*/
protected $_productFactory;
/**
* Currency factory
*
* @var CurrencyFactory
*/
protected $_currencyFactory;
/**
* Advanced Collection Factory
*
* @var ProductCollectionFactory
*/
protected $productCollectionFactory;
protected $logger;
/**
* Construct
*
* @param Context $context
* @param Registry $registry
* @param AttributeCollectionFactory $attributeCollectionFactory
* @param Visibility $catalogProductVisibility
* @param Config $catalogConfig
* @param CurrencyFactory $currencyFactory
* @param ProductFactory $productFactory
* @param StoreManagerInterface $storeManager
* @param ProductCollectionFactory $productCollectionFactory
* @param AdvancedFactory $advancedFactory
* @param array $data
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
Context $context,
Registry $registry,
AttributeCollectionFactory $attributeCollectionFactory,
Visibility $catalogProductVisibility,
Config $catalogConfig,
CurrencyFactory $currencyFactory,
ProductFactory $productFactory,
StoreManagerInterface $storeManager,
ProductCollectionFactory $productCollectionFactory,
AdvancedFactory $advancedFactory,
PsrLogLoggerInterface $loggerinterface,
array $data =
) {
$this->_attributeCollectionFactory = $attributeCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
$this->_catalogConfig = $catalogConfig;
$this->_currencyFactory = $currencyFactory;
$this->_productFactory = $productFactory;
$this->_storeManager = $storeManager;
$this->productCollectionFactory = $productCollectionFactory;
$this->logger = $loggerinterface;
parent::__construct(
$context,
$registry,
$attributeCollectionFactory,
$catalogProductVisibility,
$catalogConfig,
$currencyFactory,
$productFactory,
$storeManager,
$productCollectionFactory,
$advancedFactory,
$data
);
}
/**
* Add advanced search filters to product collection
*
* @param array $values
* @return $this
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function addFilters($values)
{
$attributes = $this->getAttributes();
$allConditions = ;
foreach ($attributes as $attribute) {
/* @var $attribute Attribute */
if (!isset($values[$attribute->getAttributeCode()])) {
continue;
}
$value = $values[$attribute->getAttributeCode()];
$preparedSearchValue = $this->getPreparedSearchCriteria($attribute, $value);
if (false === $preparedSearchValue) {
continue;
}
$this->addSearchCriteria($attribute, $preparedSearchValue);
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
if ($attribute->getBackendType() == 'datetime') {
$value['from'] = (isset($value['from']) && !empty($value['from']))
? date('Y-m-dTH:i:sZ', strtotime($value['from']))
: '';
$value['to'] = (isset($value['to']) && !empty($value['to']))
? date('Y-m-dTH:i:sZ', strtotime($value['to']))
: '';
}
$condition = $this->_getResource()->prepareCondition(
$attribute,
$value,
$this->getProductCollection()
);
if ($condition === false) {
continue;
}
$table = $attribute->getBackend()->getTable();
if ($attribute->getBackendType() == 'static') {
$attributeId = $attribute->getAttributeCode();
} else {
$attributeId = $attribute->getId();
}
$allConditions[$table][$attributeId] = $condition;
}
if ($allConditions) {
$this->_registry->register('advanced_search_conditions', $allConditions);
$this->getProductCollection()->addFieldsToFilter($allConditions);
} else {
throw new LocalizedException(__('Please specify at least one search term.'));
}
return $this;
}
/**
* Retrieve array of attributes used in advanced search
*
* @return array|MagentoCatalogModelResourceModelProductAttributeCollection
*/
public function getAttributes()
{
$attributes = $this->getData('attributes');
if ($attributes === null) {
$product = $this->_productFactory->create();
$attributes = $this->_attributeCollectionFactory
->create()
->addHasOptionsFilter()
->addDisplayInAdvancedSearchFilter()
->addStoreLabel($this->_storeManager->getStore()->getId())
->setOrder('main_table.attribute_id', 'asc')
->load();
foreach ($attributes as $attribute) {
$attribute->setEntity($product->getResource());
}
$this->setData('attributes', $attributes);
}
return $attributes;
}
/**
* Retrieve advanced search product collection
*
* @return Collection
*/
public function getProductCollection()
{
if ($this->_productCollection === null) {
$collection = $this->productCollectionFactory->create();
$this->prepareProductCollection($collection);
if (!$collection) {
return $collection;
}
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
/**
* Prepare product collection
*
* @param Collection $collection
* @return $this
*/
public function prepareProductCollection($collection)
{
$collection
->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
->setStore($this->_storeManager->getStore())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter()
->setVisibility($this->_catalogProductVisibility->getVisibleInSearchIds());
return $this;
}
/**
* @param EntityAttribute $attribute
* @param mixed $value
* @return void
*/
protected function addSearchCriteria($attribute, $value)
{
if (!empty($value)) {
$this->_searchCriterias = ['name' => $attribute->getStoreLabel(), 'value' => $value];
}
}
/**
* Add data about search criteria to object state
*
* @todo: Move this code to block
*
* @param EntityAttribute $attribute
* @param mixed $value
* @return string|bool
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function getPreparedSearchCriteria($attribute, $value)
{
if (is_array($value)) {
if (isset($value['from']) && isset($value['to'])) {
if (!empty($value['from']) || !empty($value['to'])) {
if (isset($value['currency'])) {
/** @var $currencyModel Currency */
$currencyModel = $this->_currencyFactory->create()->load($value['currency']);
$from = $currencyModel->format($value['from'], , false);
$to = $currencyModel->format($value['to'], , false);
} else {
$currencyModel = null;
}
if (strlen($value['from']) > 0 && strlen($value['to']) > 0) {
// -
$value = sprintf(
'%s - %s',
$currencyModel ? $from : $value['from'],
$currencyModel ? $to : $value['to']
);
} elseif (strlen($value['from']) > 0) {
// and more
$value = __('%1 and greater', $currencyModel ? $from : $value['from']);
} elseif (strlen($value['to']) > 0) {
// to
$value = __('up to %1', $currencyModel ? $to : $value['to']);
}
} else {
return '';
}
}
}
if (($attribute->getFrontendInput() == 'select' ||
$attribute->getFrontendInput() == 'multiselect') && is_array($value)
) {
foreach ($value as $key => $val) {
$value[$key] = $attribute->getSource()->getOptionText($val);
if (is_array($value[$key])) {
$value[$key] = $value[$key]['label'];
}
}
$value = implode(', ', $value);
} elseif ($attribute->getFrontendInput() == 'select' || $attribute->getFrontendInput() == 'multiselect') {
$value = $attribute->getSource()->getOptionText($value);
if (is_array($value)) {
$value = $value['label'];
}
} elseif ($attribute->getFrontendInput() == 'boolean') {
$value = $value == 1
? __('Yes')
: __('No');
}
return $value;
}
/**
* Returns prepared search criterias in text
*
* @return array
*/
public function getSearchCriterias()
{
return $this->_searchCriterias;
}
}
With in the Price Section, I have change like this.
if ($attribute->getAttributeCode() == 'price') {
$rate = 1;
$store = $this->_storeManager->getStore();
$currency = $store->getCurrentCurrencyCode();
if ($currency != $store->getBaseCurrencyCode()) {
$rate = $store->getBaseCurrency()->getRate($currency);
}
if(is_array($value)){
$value['from'] = (isset($value['from']) && is_numeric($value['from']))
? (float)$value['from'] / $rate
: '';
$value['to'] = (isset($value['to']) && is_numeric($value['to']))
? (float)$value['to'] / $rate
: '';
}else{
}
}
Then, Clear cache and Check it let me know if you have issue.
edited Sep 1 '17 at 3:36
answered Sep 1 '17 at 3:00
Rajkumar .ERajkumar .E
1,66551541
1,66551541
1
How to add Layered navigation on Custom Product Collection? I am displaying products by brand using custom controller.
– Magecode
Sep 1 '17 at 4:53
add a comment |
1
How to add Layered navigation on Custom Product Collection? I am displaying products by brand using custom controller.
– Magecode
Sep 1 '17 at 4:53
1
1
How to add Layered navigation on Custom Product Collection? I am displaying products by brand using custom controller.
– Magecode
Sep 1 '17 at 4:53
How to add Layered navigation on Custom Product Collection? I am displaying products by brand using custom controller.
– Magecode
Sep 1 '17 at 4:53
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f191471%2fmagento-2-layered-navigation-on-advanced-search-result-page%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown