Magento 2 Set Order not working
-
03-03-2021 - |
Question
I'm trying to set Custom Sort Order in Collection using afterSetCollection()
Following is my code 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">
<type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
<plugin name="sortby_extend_default_sort_filters" type="Package\Module\Plugin\Toolbar" sortOrder="99" />
</type>
</config>
Following is my Toolbar.php
public function afterSetCollection($collection, \Magento\Catalog\Block\Product\ProductList\Toolbar $result)
{
$collection = $result->getCollection();
$currentOrder = $result->getCurrentOrder();
$currentDirection = $result->getCurrentDirection();
if ($currentOrder && $currentOrder == 'price') {
$result->getCollection()->getSelect()->order(new \Zend_Db_Expr('new_price ' . $currentDirection));
//Following is also not working
$result->getCollection()->setOrder('new_price',$currentDirection);
}
return $result;
}
When I try to print select query in list.phtml
I get sorting only for follwoing
`e`.`entity_id` DESC
Can anyone suggest, Why my sorting not applied?
FYI : new_price
is created on the fly which working properly in aroundSetCollection()
but not working for afterSetCollection()
La solution
I found that in another(in afterSetCollection()
) file following code was given
$collection->getSelect()->reset(\Zend_Db_Select::ORDER);
Due this it was not working.
Removing above line has solved issue for me.
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange