Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento : how to change item price when adding it into the cart

Tags:

magento

cart

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

like image 613
Laurent Avatar asked Dec 28 '22 14:12

Laurent


1 Answers

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

    }
like image 196
Xman Classical Avatar answered Mar 24 '23 09:03

Xman Classical