![](/img/trans.png)
[英]Magento 2.3.5: Add product to cart with custom options and price
[英]Magento php add to cart with Custom price
我有以下問題:我在前端通過jQuery進行計算,並希望將產品添加到具有前端計算價格的購物車中。
我已經用AjaxController編寫了一個自定義模塊,以實現添加到購物車部件,但是我知道在設置自定義價格時會遇到困難。
我的腳本如下所示:
$_prod = json_decode(Mage::app()->getRequest()->getPost('zapfsaeule_product'));
$id = 347; // there is only this one bundle product added to the cart viar this scipt, so a static id is enough.
$params = array(
'product' => $id,
'related_product' => null,
'bundle_option' => array(
6 => 17, // static options for testing purpouses
5 => 13), //
'qty' => 1 // static qty for testing as well
);
$cart = Mage::getSingleton('checkout/cart');
$product = new Mage_Catalog_Model_Product();
$product->load($id);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$this->getResponse()->setBody('true'); // setting response to true, because its an ajax request.
$this->getResponse()->setHeader('Content-type', 'text/plain');
這就是添加產品的代碼。 為了設置價格,我嘗試了該線程在stackexchange上提到的方法: https : //magento.stackexchange.com/questions/4318/dynamically-calculated-prices-save-before-add-to-cart
但這沒有用。 我想這里觀察到的事件不會發生,因為我寫了一個自定義腳本。
但是,如果觀察者方法可行,那么仍然會有問題,我如何將計算出的價格傳遞給觀察者?
希望您能理解該問題並能幫助我解決。
提前致謝!
最好的問候,馬丁
通過閱讀Mage_Checkout_Model_Cart::addProduct()
,似乎沒有一種方法可以通過參數設置商品的價格。 相反,您需要添加產品,然后獲取生成的商品並設置其價格:
$cart->addProduct($product, $params)
->save();
// grab the corresponding item
$item = $cart->getQuote()->getItemByProduct($product);
// set its custom price
$item->setOriginalCustomPrice($customPrice)
->save();
還沒有時間嘗試一下,但這應該是正確的想法。 確保您設置了original_custom_price
字段(使用setOriginalCustomPrice()
),而不是其他價格之一。 在總計過程中將重新計算其他價格。
這來晚了,但是我偶然發現了這一點。
我讓它像這樣工作:
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct($product, 1); // 1 = qty. Pass your qty and params.
$item = $cart->getQuote()->getItemByProduct($product);
$item->setCustomPrice(0); // or some other value
$item->setOriginalCustomPrice(0); // or some other value
$item->getProduct()->setIsSuperMode(true); // this is crucial
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
如果參數不起作用,請在保存購物車之前從$cart->addProduct
獲取返回的商品並更改商品價格。
$item = $cart->addProduct(...);
$item->setCustomPrice(...); {or whatever price attribute you like to set}
$cart->save();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.