根据自定义价格以编程方式将产品添加到购物车:Magento 2

问题描述 投票:3回答:2

我有一个使用Magento报价模块创建报价的模块。

现在我想继续结帐,应该将报价项目添加到购物车,结账页面应该显示给用户,包含报价中的那些项目。

在这里,我创建引号为:

$quote = $this->quoteFactory->create()->load($quoteId);

报价创造良好,我得到报价中的项目:

$items = $quote->getAllItems();

我将产品添加到购物车如下,

$items = $quote->getAllItems();

foreach ($items as $item) {
    $formatedPrice = $item->getPrice();
    $quantity = $item['qty'];
    $productId = $item->getProductId();

    $params = array(
          'form_key' => $this->formKey->getFormKey(),
          'product' => $productId, //product Id
          'qty' => $quantity, //quantity of product
          'price' => $formatedPrice //product price
    );

    $_product = $this->_productRepository->getById($productId);

    if ($_product) {
        $this->cart->addProduct($_product, $params);
    }
}
try {
    $this->cart->save();
    $this->messageManager->addSuccess(__('Added to cart successfully.'));
} catch (\Magento\Framework\Exception\LocalizedException $e) {
    $this->messageManager->addException($e, __('%1', $e->getMessage()));
}

这里的问题是物品被添加到购物车中但是如果有产品具有定制价格,我需要将这些产品添加到购物车,其价格与目录中产品的配置价格不同。

定制价格定义在,

$formatedPrice = $item->getPrice();

此外,我遇到一个问题,每当我创建一个新的报价并将之前的报价添加到购物车时,它会显示所创建的最新报价的项目。当引用ID在这里正确时,怎么会发生这种情况。

我实际上想在Magento 2中做这样的事情:Programmatically add product to cart with price change

请问,任何人都可以帮忙解决这个问题吗?

magento2 cart quote
2个回答
0
投票

工作解决方案,如果你考虑它真的很容易:

$params = array(
  'form_key' => $this->_formKey->getFormKey(),
  'product' => $productId,
  'qty'   => $qty
);

$product = $this->_product->load($productId); 
$product->setPrice($customPrice); // without save this does the trick
$this->cart->addProduct($product, $params);
$this->cart->save();

丢失的部分可以随意填写。


0
投票

这在Magento 2.2.8中对我有用:

在控制器中:

        $price = rand(0,1000);

        $this->product->setData('custom_overwrite_price', $price);

        $params = [
            'form_key' => $this->formKey->getFormKey(),
            'qty' => 1,
            'options' => ...
        ];

        $this->cart->addProduct($this->product, $params);
        $this->cart->save();

在checkout_cart_product_add_after中

public function execute(\Magento\Framework\Event\Observer $observer) {
    $item = $observer->getEvent()->getData('quote_item');
    $item = ( $item->getParentItem() ? $item->getParentItem() : $item );

    $price = $item->getProduct()->getData(AddController::PRODUCT_OVERWRITE_PRICE);

    $item->setCustomPrice($price);
    $item->setOriginalCustomPrice($price);
    $item->getProduct()->setIsSuperMode(true);
}
© www.soinside.com 2019 - 2024. All rights reserved.