4

I have custom price field for specific product where user can input their desire product price, and i try to add the product to the cart programmatically, the problem is i need to change the product price to price which the user input, here's what i've got so far:

    $qty = $_REQUEST['qty'];
    $price = $_REQUEST['price'];
    $finalPrice = $price / $qty;

    $sku = 'BLA-01';
    $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
    /*
     need to chage the product price here
     $product->setCustomPrice($finalPrice);
    */
    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $params = array(
        'product' => $product->getId(),
        'qty' => $qty,
        'form_key' => Mage::getSingleton('core/session')->getFormKey(),
    );
    $request = new Varien_Object();
    $request->setData($params);
    try {
        $cart->addProduct($product->getId(), $request);
        $cart->save(); 
    } catch (Exception $e) {
        print_r($e->getMessage());
    }
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

1 Answer 1

4

Since you need it based on $_REQUEST data, you need to add the product to the cart first than you can change the price, usually i use it in observer. here's the function code:

private function modifyPrice($product_id,$newPrice){
    //get quote
    $quote = Mage::getSingleton('checkout/session')->getQuote();

    foreach ($quote->getAllVisibleItems() as $item) {
        //for specific product
         if($item->getProduct()->getId() != $product_id) continue;

         if ($newPrice > 0) {
                 $item->setCustomPrice($newPrice);
                 $item->setOriginalCustomPrice($newPrice);
                 $item->getProduct()->setIsSuperMode(true);
         }
    }
    //don't forget to save the quote
    $quote->save();
}

call this function after this code:

Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.