I need to add an option in the Sort By
dropdown which sorts the products with based on stock availability
of the products.
So far i have created a plugin for setCollection
methodMagento\Catalog\Block\Product\ProductList\Toolbar
.
Check the following code i am using to apply the sort order
public function afterSetCollection($subject)
{
$selectedDirection = strtolower($this->_toolbarModel->getDirection());
if($this->_toolbarBlock->getCurrentOrder() == 'stock'){
$collection = $subject->getCollection();
$collection->addAttributeToSort('is_in_stock',$selectedDirection);
$collection->getSelect()->joinLeft(
['_inventory_table' => 'cataloginventory_stock_item'],
"_inventory_table.product_id = e.entity_id",
['is_in_stock']
);
$collection->getSelect()->order('is_in_stock',$selectedDirection);
$collection->setOrder('is_in_stock',$selectedDirection);
/*echo $collection->getSelect();die;*/
}
return $subject;
}
When i print the sql query, it shows the Order By
clause applied and if i execute it, it generates correct results, but the product list in the list page does not reflect the same order.