Magento 2, adding desc and asec to sorter seletion
-
10-12-2020 - |
Question
The requirement is displaying the asce
and desc
for each option in <select id="sorter" data-role="sorter" class="sorter-options">
. Like price asce
, price desc
. I changed the default code to below, option works but how trigger asce or desc while choosing the option?
in my custom theme templates/product/list/toolbar/sorter.phtml
<select id="sorter" data-role="sorter" class="sorter-options">
<?php foreach ($block->getAvailableOrders() as $_key => $_order): ?>
<option value="<?php /* @escapeNotVerified */
echo $_key; ?>"
<?php if ($block->isOrderCurrent($_key)): ?>
selected="selected"
<?php endif; ?>
>
<?php echo $block->escapeHtml(__($_order)) ?> <a title="<?php /* @escapeNotVerified */
echo __('Set Ascending Direction') ?>" href="#" class="action sorter-action sort-desc"
data-role="direction-switcher" data-value="asc">
<span><?php /* @escapeNotVerified */
echo __('Set Ascending Direction') ?></span>
</a>
<option value="<?php /* @escapeNotVerified */
echo $_key; ?>"
<?php if ($block->isOrderCurrent($_key)): ?>
selected="selected"
<?php endif; ?>
>
<?php echo $block->escapeHtml(__($_order)) ?> <a title="<?php /* @escapeNotVerified */
echo __('Set Descending Direction') ?>" href="#" class="action sorter-action sort-asc"
data-role="direction-switcher" data-value="desc">
<span><?php /* @escapeNotVerified */
echo __('Set Descending Direction') ?></span>
</a>
</option>
<?php endforeach; ?>
</select>
Solution
You must have to override the getAvailableOrder() and setCollection() function of the Magento
/vendor/magento/module-catalog/Block/Product/ProductList/Toolbar.php
Below is the code which may help you.
public function aroundGetAvailableOrders(\Magento\Catalog\Block\Product\ProductList\Toolbar $subject, \Closure $proceed)
{
$returnValue = $proceed();
unset($returnValue['price']);
$returnValue['priceDesc'] = 'price - high to low';
$returnValue['priceAsc'] = 'price - low to high';
return $returnValue;
}
public function aroundSetCollection(\Magento\Catalog\Block\Product\ProductList\Toolbar $subject, \Closure $proceed, $collection)
{
$returnValue = $proceed($collection);
if ($subject->getCurrentOrder() == 'priceHighToLow') {
$collection->addAttributeToSelect('*')->setOrder('price', 'ASC');
$collection->load();
}
return $collection;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange