문제

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 ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top