magentoobserversmagento-1.9.1

How to Change the price before adding to cart in magento?


How to Change the product price while adding to cart Magento, Example :

suppose I am trying to add 1 product of price $10, I want to show the price with $10*5 = $50, when I add 2 products I want to show $10*10 = $100. so its common multiplier is 5.(multiples of x).


Solution

  • Create Observer.php file in app/community/Custom_Module/Modulename/Model copy the below code inside that file.

    class Custom_Module_Modulename_Model_Observer
    {
        public function _construct()
        {
        }
    
        public function getNewPrice()
        {
    
            $login  = Mage::getSingleton('customer/session')->isLoggedIn();
            $roleId = Mage::getSingleton('customer/session')->getCustomerGroupId();
            $userrole   = Mage::getSingleton('customer/group')->load($roleId)->getData('customer_group_code');
            $userrole   = strtolower($userrole);
            $quote = Mage::getSingleton('checkout/session')->getQuote();
            $cartItems = $quote->getAllVisibleItems();
            foreach ($cartItems as $item) {
                $productId = $item->getProductId();
                $product = Mage::getModel('catalog/product')->load($productId);
            }
            $batch_qty = $product->getBatchQty();
            $actualPrice = $product->getPrice();
            $specialPrice = $product->getFinalPrice();
            if (isset($batch_qty) && $userrole=="retailer") {
                if (isset($specialPrice)) {
                    $newprice = $specialPrice*$batch_qty;
                } else {
    
                    $newprice = $actualPrice*$batch_qty;
                }
    
            } else {
                $newprice= $actualPrice;
            }
    
            return $newprice;
        }
    
        public function updatePrice($observer)
        {
            $event = $observer->getEvent();
            $product = $event->getProduct();
            $quote_item = $event->getQuoteItem();
            $new_price = $this->getNewPrice();
            $quote_item->setOriginalCustomPrice($new_price);
            //$quote_item->save();
            $quote_item->getQuote()->save();
            //Mage::getSingleton('checkout/cart')->save();
        }
    
    }
    

    Copy the below code and paste it your app/community/Custom_Module/Modulename/etc/config.xml inside tag

    > <events>            
    >           <sales_quote_add_item>
    >               <observers>
    >                  <Custom_Module_Modulename_model_observer>
    >                     <type>singleton</type>
    >                     <class>Custom_Module_Modulename_Model_Observer</class>
    >                     <method>updatePrice</method>
    >                  </Custom_Module_Modulename_model_observer>
    >              </observers>
    >           </sales_quote_add_item>
    >       </events>
    

    This is working fine for me.