4

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

Community
  • 1
  • 1
Laurent
  • 440
  • 1
  • 4
  • 11

1 Answers1

10

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;
        }

    }
Xman Classical
  • 5,179
  • 1
  • 26
  • 26
  • If 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 formatPrice($_item->getRowTotal()) ?> – Mukesh Jan 20 '14 at 16:10
  • Can anyone explain `setIsSuperMode` from this line `$item->getProduct()->setIsSuperMode(true);`? What does it do? – mkutyba Feb 06 '15 at 00:21
  • 2
    Here 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 – Nidheesh Apr 17 '15 at 10:01