Reputation: 175
I am trying to remove just one qty from my cart rather than all, but to no avail.
Can anybody help?
Here is the code I have got so far...
require_once 'app/Mage.php';
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");
$yourProId = $_POST['prodID'];
$qty = 1;
foreach (Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item) {
if ($yourProId == $item->getProductId()) {
Mage::getSingleton('checkout/cart')->removeItem($item->getId())->save();
}
}
UPDATE: Here is the code that works, thanks to R.S. for this!
$yourProId = $_POST['prodID'];
$qty=1;
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $yourProId) {
$qty = $item->getQty() - 1; // check if greater then 0 or set it to what you want
if($qty == 0) {
Mage::getSingleton('checkout/cart')->removeItem($item->getId());
} else {
$item->setQty($qty);
}
$cartHelper->getCart()->save();
break;
}
}
Upvotes: 1
Views: 6020
Reputation: 126
For Magento 2 you can utilize https://yourdomain.com/rest/V1/carts/mine/items API with Auth token and Body
{
"cartItem": {
"item_id": 49388,//item_id not SKU
"qty": 1, //This will overwrite quantity
"quote_id": {{QuoteId}}
}
}
Upvotes: 0
Reputation: 330
You can alter or remove qty using $quoteItem->setData('qty', $avl_qty); Please refer to code for more help.
$quoteItem = $observer->getEvent()->getQuoteItem();
$avl_qty = 1;
if ($avl_qty == '0') {
$quoteItem->getQuote()->removeItem($quoteItem->getItemId());
throw new LocalizedException(__("This product is currently out of stock."));
}
elseif ($order_qty > $avl_qty) {
$quoteItem->setData('qty', $avl_qty);
$this->_cart->save();
$this->messageManager->addNoticeMessage('Sorry we have only '.$avl_qty.' qty of this product available');
}
else {
}
Upvotes: 0
Reputation: 17656
Try
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $yourProId) {
if( $item->getQty() == 1 ){
$cartHelper->getCart()->removeItem($item->getItemId())->save();
}
else if($item->getQty() > 1){
$item->setQty($item->getQty() - 1)
$cartHelper->getCart()->save();
}
break;
}
}
Take a look @ /app/code/core/Mage/Checkout/controllers/CartController.php
See http://www.magentocommerce.com/boards/viewthread/30113/
Upvotes: 4