Wednesday, July 18, 2012

Add Product to Cart with Price Change

If you want to add a product to the cart after change its price, then you have to write an Observer that listens the checkout_cart_product_add_after or checkout_cart_update_items_after event. The code is same except checkout_cart_product_add_after is called for only one item and checkout_cart_update_items_after is called for all items in the cart.


/**
* @param Varien_Event_Observer $observer
*/
public function myDiscount(Varien_Event_Observer $observer)
{
$item = $observer->getQuoteItem();
if ($item->getParentItem()) {
$item = $item->getParentItem();
}

//discount 20% off
$discount = 0.20;

// Check if the discount isn't applied over and over while refreshing
$specialPrice = $item->getOriginalPrice() - ($item->getOriginalPrice() * $discount);

if ($specialPrice > 0) {
$item->setCustomPrice($specialPrice);
$item->setOriginalCustomPrice($specialPrice);
$item->getProduct()->setIsSuperMode(true);
}
}