根据定制价格以编程方式将产品添加到购物车: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个回答
1
投票

这在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('custom_overwrite_price');

    $item->setCustomPrice($price);
    $item->setOriginalCustomPrice($price);
    $item->getProduct()->setIsSuperMode(true);
}

-1
投票

有效的解决方案,如果您考虑的话,真的很容易:

$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();

缺少的片段可以随意填写。

© www.soinside.com 2019 - 2024. All rights reserved.