php - 在 Magento 2 中以编程方式将新产品添加到现有购物车时,产品价格为 0
问题描述
我的目标:
Magento 2.2.5
如果客户勾选了[添加购物袋]选项然后点击[继续购买],我会将[购物袋]产品添加到购物车并重定向到确认页面。
源代码:
public function addShoppingBag()
{
$shoppingBagSku = $this->helper->getShoppingBagSku();
$shoppingBagId = $this->productRepository->get($shoppingBagSku)->getId();
$shoppingBagProduct = $this->productFactory->create()->load($shoppingBagId);
$quote = $this->checkoutSession->getQuote();
$params = array(
'product' => $shoppingBagProduct->getId(),
'qty' => 1,
'price' => intval($shoppingBagProduct->getPrice())
);
$request = new \Magento\Framework\DataObject();
$request->setData($params);
$quote->addProduct($shoppingBagProduct, $request);
$quote->getShippingAddress()->setCollectShippingRates(true);
$this->quoteRepository->save($quote);
$quote->collectTotals();
}
问题:
我检查了quote_item表,添加了产品,但与价格相关的所有属性都是 0。quote_address_item表很好,所有价格都是正确的。问题仅在于quote_item。
我试过的东西
$this->cart->addProduct($shoppingBagProduct, $request);
$this->cart->save();
$this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
quote_item 价格将被更新,但由于以下代码,它将再次重定向到购物车页面:
/magento2/source/vendor/magento/module-multishipping/Controller/Checkout.php
if ($this->_getCheckoutSession()->getCartWasUpdated(true)
&&
!in_array($action, ['index', 'login', 'register', 'addresses', 'success'])
) {
$this->getResponse()->setRedirect($this->_getHelper()->getCartUrl());
$this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
return parent::dispatch($request);
}
当我尝试:
setCartWasUpdated(false)
它根据我的需要重定向到确认页面,但 quote_item 价格仍然为 0。
系统 > 配置 > 销售 > 结帐 > 将产品重定向到购物车后设置为否
问题:
我在谷歌搜索了很多相同的问题,但没有运气归档我的目标。可能是我在这里遗漏了一些东西,任何建议将不胜感激。感谢您阅读我的问题。
解决方案
我需要在添加产品之前设置 multishiping = false。
$quote->setIsMultiShipping(false);
$quote->addProduct($this->getShoppingBagProduct(), $quantity);