How to update cart item using item ID ? I have searched a lot but could not success, here is my codes -
require_once '../app/Mage.php';
Mage::app('default');
$qty = $_REQUEST['quantity'];
$item_id = (int) $_REQUEST['item_id'];
$cart = Mage::getSingleton('checkout/cart');
$quoteItem = $cart->getQuote()->getItemById($item_id);
/*$quoteItem = Mage::getModel('sales/quote_item')->getCollection()
->addFieldToFilter('item_id', array('in' => array($item_id)));*/
print_r($quoteItem);
if (!$quoteItem) {
Mage::throwException('Quote item is not found.');
}
if ($qty == 0) {
$cart->removeItem($id);
} else {
$quoteItem->setQty($qty)->save();
}
$cart->save();
I am implementing it in API , however same code is working fine in website.Please help!!!
I used the below code to update cart items and I am using observer to do that. can you please try this.
$quote = $observer->getEvent()->getQuote();
var_dump($quote->getId());
$quote = Mage::getSingleton('checkout/session')->getQuote();
//var_dump($quote->getId());
$cartItems = $quote->getAllItems();
//$storeId = Mage::app()->getStore()->getId();
foreach ($cartItems as $item) {
//echo $item->getSku();
$item->set__($value); // desired quote field from database
$item->save();
}
$quote->save();
Related
I am trying to split order by using product's manufacturer attribute.Like if there are 3 products in cart as 2 lee(manufacturer) products and 1 Levis(manufacturer) product.So when we place order it should generate 2 order one for lee and other one is for levis.
So with some help i am able to split order(problem in total but's it's ok)but it's creating order per product like 5 product 5 orders, so i am just asking is it possible to do as i want?
Here is code for split order which i am using currently
class PMTECH_Splitorder_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage
{
/**
* Create order based on checkout type. Create customer if necessary.
*
* #return Mage_Checkout_Model_Type_Onepage
*/
public function saveOrder()
{
$this->validate();
$isNewCustomer = false;
switch ($this->getCheckoutMethod()) {
case self::METHOD_GUEST:
$this->_prepareGuestQuote();
break;
case self::METHOD_REGISTER:
$this->_prepareNewCustomerQuote();
$isNewCustomer = true;
break;
default:
$this->_prepareCustomerQuote();
break;
}
$cart = $this->getQuote();
$key=0;
foreach ($cart->getAllItems() as $item)
{
$key= $key+1;
$temparray[$key]['product_id']= $item->getProduct()->getId();
$temparray[$key]['qty']= $item->getQty();
$cart->removeItem($item->getId());
$cart->setSubtotal(0);
$cart->setBaseSubtotal(0);
$cart->setSubtotalWithDiscount(0);
$cart->setBaseSubtotalWithDiscount(0);
$cart->setGrandTotal(0);
$cart->setBaseGrandTotal(0);
$cart->setTotalsCollectedFlag(false);
$cart->collectTotals();
}
$cart->save();
foreach ($temparray as $key => $item)
{
$customer_id = Mage::getSingleton('customer/session')->getId();
$store_id = Mage::app()->getStore()->getId();
$customerObj = Mage::getModel('customer/customer')->load($customer_id);
$quoteObj = $cart;
$storeObj = $quoteObj->getStore()->load($store_id);
$quoteObj->setStore($storeObj);
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->load($item['product_id']);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setBasePrice($productObj->getFinalPrice());
$quoteItem->setPriceInclTax($productObj->getFinalPrice());
$quoteItem->setData('original_price', $productObj->getPrice());
$quoteItem->setData('price', $productObj->getPrice());
$quoteItem->setRowTotal($productObj->getFinalPrice());
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty($item['qty']);
$quoteItem->setStoreId($store_id);
$quoteObj->addItem($quoteItem);
$quoteObj->setBaseSubtotal($productObj->getFinalPrice());
$quoteObj->setSubtotal($productObj->getFinalPrice());
$quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
$quoteObj->setGrandTotal($productObj->getFinalPrice());
$quoteObj->setStoreId($store_id);
$quoteObj->collectTotals();
$quoteObj->save();
$this->_quote=$quoteObj;
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
if ($isNewCustomer) {
try {
$this->_involveNewCustomer();
} catch (Exception $e) {
Mage::logException($e);
}
}
$this->_checkoutSession->setLastQuoteId($quoteObj->getId())
->setLastSuccessQuoteId($quoteObj->getId())
->clearHelperData();
$order = $service->getOrder();
if ($order) {
Mage::dispatchEvent('checkout_type_onepage_save_order_after',
array('order'=>$order, 'quote'=>$quoteObj));
$quoteObj->removeAllItems();
$quoteObj->setTotalsCollectedFlag(false);
$quoteObj->collectTotals();
}
/**
* a flag to set that there will be redirect to third party after confirmation
* eg: paypal standard ipn
*/
$redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
/**
* we only want to send to customer about new order when there is no redirect to third party
*/
if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e) {
Mage::logException($e);
}
}
// add order information to the session
$this->_checkoutSession->setLastOrderId($order->getId())
->setRedirectUrl($redirectUrl)
->setLastRealOrderId($order->getIncrementId());
// as well a billing agreement can be created
$agreement = $order->getPayment()->getBillingAgreement();
if ($agreement) {
$this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
}
}
// add recurring profiles information to the session
$profiles = $service->getRecurringPaymentProfiles();
if ($profiles) {
$ids = array();
foreach ($profiles as $profile) {
$ids[] = $profile->getId();
}
$this->_checkoutSession->setLastRecurringProfileIds($ids);
// TODO: send recurring profile emails
}
Mage::dispatchEvent(
'checkout_submit_all_after',
array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
);
return $this;
}
}
And i think it will be helpful to insert data in flat order quote item so i have that field in this table with product's manufacturer id inserted in it
Thank you in advance for any help.
I found solution on my own, posting answer so may be it can help someone.
i am posting what i made changes in code.
foreach ($cart->getAllItems() as $item)
{
$key= $key+1;
$product = Mage::getModel('catalog/product')->load($item->getProduct()->getId());
$temparray[$product->getManufacturer()][] = array('product_id'=>$item->getProduct()->getId(),'qty'=>$item->getQty());
//added this above line for grouping products by brands
$cart->removeItem($item->getId());
$cart->setSubtotal(0);
$cart->setBaseSubtotal(0);
$cart->setSubtotalWithDiscount(0);
$cart->setBaseSubtotalWithDiscount(0);
$cart->setGrandTotal(0);
$cart->setBaseGrandTotal(0);
$cart->setTotalsCollectedFlag(false);
$cart->collectTotals();
}
$cart->save();
foreach ($temparray as $key => $items)
{ // this ends as it is in my question code
foreach($items as $item){ //added this foreach
$customer_id = Mage::getSingleton('customer/session')->getId();
$store_id = Mage::app()->getStore()->getId();
$customerObj = Mage::getModel('customer/customer')->load($customer_id);
$quoteObj = $cart;
$storeObj = $quoteObj->getStore()->load($store_id);
$quoteObj->setStore($storeObj);
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->load($item['product_id']);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setBasePrice($productObj->getFinalPrice());
$quoteItem->setPriceInclTax($productObj->getFinalPrice());
$quoteItem->setData('original_price', $productObj->getPrice());
$quoteItem->setData('price', $productObj->getPrice());
$quoteItem->setRowTotal($productObj->getFinalPrice() * $item['qty']);
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty($item['qty']);
$quoteItem->setManufacturerName($key);//not sure about this that i need to add this or not
$quoteItem->setStoreId($store_id);
$quoteObj->addItem($quoteItem);
$quoteObj->setBaseSubtotal($productObj->getFinalPrice());
$quoteObj->setSubtotal($productObj->getFinalPrice());
$quoteObj->setBaseGrandTotal($productObj->getFinalPrice());
$quoteObj->setGrandTotal($productObj->getFinalPrice());
$quoteObj->setStoreId($store_id);
$quoteObj->collectTotals();
$quoteObj->save();
$this->_quote=$quoteObj;
}
Okay so by doing this now i am able to split order by brand as i want.
The following function is on carts page, after a user has added product from previous product page. The problem is I need the multidimensional array just to update quantity in cart for same product code being added.
Can someone help me add an if statement so when the same productcode is added quantity increases?
Like this answer however my add to cart is different. PHP Sessions shopping cart: update product if it's already id the session
function AddToCart()
{
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : '';
$itemcount = isset($_SESSION
['itemcount']) ? $_SESSION['itemcount'] : 0;
{
$i = array_search($_POST['productcode'], $cart[PRODUCTCODE]);
$cart[PRODUCTCODE] [$itemcount] = $_POST['productcode'];
$cart[PRODUCTNAME] [$itemcount] = $_POST['productname'];
$cart[QUANTITY][$itemcount] = intval($_POST['quantity']);
$cart[PRICE][$itemcount] = $_POST['price'];
$itemcount = $itemcount + 1;
if(strlen($error) == 0) {
$_SESSION['cart'] = $cart;
$_SESSION['itemcount'] = $itemcount;
}
return $error;
}
Try this.
//check for an existing match
$found = FALSE;
if($cart){
$idx = 0;
foreach($cart[PRODUCTCODE] as $idx => $product){
if($product == $_POST['productcode']){
$found = TRUE;
break;
}
}
}
//if we found a match
if($found){
$cart[QUANTITY][$idx] += intval($_POST['quantity']);
}
//otherwise add new item
else{
//your other code here
}
I want to sort the wishlist product collection by product's date and price.
Can anyone help me out please...
Here is my code
public function getWishlistCollection(Mage_Customer_Model_Customer $customer = null){
if($customer):
$wishlists = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
if($wishlists->getItemCollection()->getSize()):
$wishlists = $this->favorites->getItemCollection();
$wishlists->addWishListSortOrder('added_at', 'DESC');
$wishlists->getSelect()->limit(10, 0);
return $wishlists;
endif;
return;
endif;
return;
}
No the item collection is not the product collection. In this case you need to create the product collection from your wishlist item collection.
Use the code below:
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer);
$wishListItemCollection = $wishList->getItemCollection();
if (count($wishListItemCollection)) {
$arrProductIds = array();
foreach ($wishListItemCollection as $item) {
$arrProductIds[] = $item->getProductId();
}
}
$productsCollection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('entity_id', array('in' => $arrProductIds))
->addAttributeToSort('price', 'ASC')
->addAttributeToSort('created_at', 'ASC');
foreach($productsCollection as $product)
{
echo $product->getprice();
echo $product->getCreatedAt();
}
In Magento 1.9.0.1 by default, it decreases stock qty while placing an order. I want to stop decreasing stock qty while placing an order for the purpose of fake order. And I also want the functionality of increasing stock qty while order state is complete, not pending, not processing. How to do it programmatically or by setting up in Admin panel. If any one knows about it, please reply back.
Thank You
Ankan
Just simply open your admin panel, go to System->Configuration->Catalog Tab->Inventory Then click on Stack Option and change Decrease Stock When Order is Placed to NO.
Thanks,
Lovekesh
In Admin panel, System->Configuration->Catalog Tab->Inventory Then click on Stack Option and change Decrease Stock When Order is Placed to NO. So that it stops the stock qty increasing.In Model/Automatically/Complete/Order/Observer.php page, class Webspidy_Customoption_Model_Automatically_Complete_Order_Observer
{ public function __construct(){}
public function automaticallycompleteorder($observer)
{
//Mage::log('Ankan');
$order = $observer->getEvent()->getOrder();
/$orders = Mage::getModel('sales/order_invoice')->getCollection()
->addAttributeToFilter('order_id', array('eq'=>$order->getId()));/
/*if ((int)$orders->count() !== 0) {
return $this;
}*/
//Mage::log($orderstate);
//if($order->getState() == 'complete'){
if(($order->getState() == 'processing') || ($order->getState() == 'pending_payment')){
if($order->hasInvoices()){
//Mage::log($orderstate);
//Mage::log('Ankan');
//Mage::log($order->getData());
//====== Order Details ================
$orderNumber = $order->getIncrementId(); //Mage::log($orderNumber);
$orderDet = Mage::getModel('sales/order')->load($orderNumber, 'increment_id');
//Mage::log($orderDet->getData());
$orderItems = $orderDet->getItemsCollection()
->addAttributeToSelect('*')
->load();
foreach($orderItems as $orderItem){
$productId = $orderItem->getProductId();
$productOptionSku = $orderItem->getSku();
$productQty = $orderItem->getQtyOrdered();
$product = Mage::getModel('catalog/product')->load($productId);
$sku = $product->getSku();
$centralqty = $product->getStockItem()->getQty();
$values = array();
foreach ($product->getOptions() as $o) {
$p = $o->getValues();
}
foreach($p as $v)
{
$optionSku = $v->getSku();
$optionItem = $v->getQty();
//Mage::log($optionItem);
//Mage::log($productOptionSku.".....".$sku."-".$optionSku.".....".$optionItem);
if($productOptionSku == ($sku."-".$optionSku)){
if($centralqty >= ($optionItem*(int)$productQty)){
//$stockQty = (($centralqty-($optionItem*(int)$productQty))+$productQty);
$stockQty = ($centralqty-($optionItem*(int)$productQty));
}
}
}
$product->save();
//Mage::log($stockQty);
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
//$stockItem = Mage::getModel('cataloginventory/stock_item')->load($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('qty', $stockQty);//(integer)$XMLproduct->QtyInStock
$stockItem->setData('manage_stock',1);
$stockItem->save();
}
}
//======== End ======
}
}
}
And in etc/config.xml,
<global><events>
<sales_order_save_after><observers>
<webspidy_customoption_automatically_complete_order_observer>
<type>singleton</type> <class>Webspidy_Customoption_Model_Automatically_Complete_Order_Observer</class>
<method>automaticallycompleteorder</method>
</webspidy_customoption_automatically_complete_order_observer>
</observers></sales_order_save_after></events></global> After a long process, I have got a success by creating Observer in my custom module.
I am using Magento 1.9
I have tried with the following code. it's OK But i have another smart code
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('qty', $stockQty);
$stockItem->setData('manage_stock',1);
$stockItem->save();
My code is following:-
Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);
Using Magento 1.8.1, on the checkout page, I'm trying to add a product to the cart in the code. Here is the code I'm using:
$totals = Mage::getSingleton('checkout/cart')->getQuote()->getTotals();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$this->addProduct($free_samples_prod_id, 1);
}
else{
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $free_samples_prod_id) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
}
The code is in: app\code\core\Mage\Checkout\Model\Cart.php under public function init()
The product does get added sucessfully, however, everytime somebody visits their cart page, the quantity increases by one. How can I modify that code so the quantity is always 1?
Thank you
Axel makes a very good point, but to answer your immediate question, why not test for the product's presence before you add it
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
$subtotal = $totals["subtotal"]->getValue();
$free_samples_prod_id = 1285;
if ( $subtotal >= 50 ) {
$alreadyAdded = false;
foreach ($items as $item) {
if($item->getId() == $free_samples_prod_id) { $alreadyAdded = true; break; }
}
if(!$alreadyAdded) { $this->addProduct($free_samples_prod_id, 1); }
}