I am trying to sort the items based on the product ordered qty.
Is there any logical method to the way cart items are sorted by ordered qty?
I am trying to sort the items based on the product ordered qty.
Is there any logical method to the way cart items are sorted by ordered qty?
You can use getItems()
plugin to Sort Quote Items:
Create This Plugin:
MODULE\etc\di.xml
<type name="Magento\Checkout\Block\Cart">
<plugin name="item_filter" type="[Your]\[Module]\Plugin\Checkout\Block\Cart" />
</type>
MODULE\Plugin\Checkout\Block\Cart:
public function afterGetItems(\Magento\Checkout\Block\Cart $subject){
$items = [];
$totalItems = [];
$itemAdded = [];
foreach ($subject->getQuote()->getAllItems() as $item) {
$totalItems[] = $item->getId();
if(/*Your Condition*/){
/*you can sort item by qty wise*/
/*you can get qty using $item->getQty();*/
$itemAdded[] = $item;
$items[] = $item;
}
}
$result = array_diff($totalItems, $itemAdded);
foreach ($result as $quoteid) {
if($quoteid){
$item = $this->cart->getQuote()->getItemById($quoteid);
$items[] = $item;
}
}
return $items;
}
Magento\Checkout\Block\Cart
, it should be Your\Module\Plugin\Checkout\Block\Cart
Commented
Aug 3, 2018 at 14:30
First create a plugin,
In di.xml use :
<type name="Magento\Checkout\CustomerData\Cart">
<plugin name="SortByQty" type="Vendor\Module\Plugin\Cart"/>
</type>
Then in Cart.php add a function afterGetSectionData,
Now the logic will be done for sorting but i can tell the starting:
public function afterGetSectionData(\Magento\Checkout\CustomerData\Cart $subject, $result){
$items = $result['items'];
foreach ($items as $key => $value) {
$_productId = $value['product_id'];
$_productPrice = $value['product_price_value'];
$_productQty = $value['qty'];
$_productTotal = $_productPrice * $_productQty;
}
$data = [
'items' => $items
];
return $result = array_merge($data, $result);
}