Magento : how to change item price when adding it into the cart
20,184
You can use an observer class to listen to checkout_cart_product_add_after, and use a product’s “Super Mode” to set custom prices against the quote item.
In your /app/code/local/{namespace}/{yourmodule}/etc/config.xml:
<config>
...
<frontend>
...
<events>
<checkout_cart_product_add_after>
<observers>
<unique_event_name>
<class>{{modulename}}/observer</class>
<method>modifyPrice</method>
</unique_event_name>
</observers>
</checkout_cart_product_add_after>
</events>
...
</frontend>
...
</config>
And then create an Observer class at /app/code/local/{namespace}/{yourmodule}/Model/Observer.php
<?php
class <namespace>_<modulename>_Model_Observer
{
public function modifyPrice(Varien_Event_Observer $obs)
{
// Get the quote item
$item = $obs->getQuoteItem();
// Ensure we have the parent item, if it has one
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
// Load the custom price
$price = $this->_getPriceByItem($item);
// Set the custom price
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
// Enable super mode on the product.
$item->getProduct()->setIsSuperMode(true);
}
protected function _getPriceByItem(Mage_Sales_Model_Quote_Item $item)
{
$price;
//use $item to determine your custom price.
return $price;
}
}
Author by
Laurent
I am a UI designer and Drupal and Magento developer. I am running my own web agency in the Paris area : Coheractio : Agence Web Paris Versailles
Updated on February 27, 2020Comments
-
Laurent over 3 years
I would like to be able to change an item price programmatically (not through catalog or cart rules) when I add it into the cart.
The following answer Programmatically add product to cart with price change shows how to do it when updating the cart but not when adding a product.
Thanks
-
Mukesh almost 10 yearsIf I add set a custom price to cart using observer, then I am getting the unit price in order email template multiplied by the item quantity. How can I fix that app\design\frontend\default\rfg\template\email\order\items\order\default.phtml <?php echo $_order->formatPrice($_item->getRowTotal()) ?>
-
mkutyba almost 9 yearsCan anyone explain
setIsSuperMode
from this line$item->getProduct()->setIsSuperMode(true);
? What does it do? -
Nidheesh over 8 yearsHere is the explantion for supermode: "Quote super mode flag mean what we work with quote without restriction" For example: If super mode is set to true, magneto won't check whether the product is visible in catalog