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);
有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
scroll top