1

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()

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.