My goal:
Magento 2.2.5
If the customer checked to [Add Shopping Bag] option then click [Proceed to Purchase], I’ll add the [Shopping Bag] product to cart and redirect to confirm page.
Source Code:
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 MagentoFrameworkDataObject();
$request->setData($params);
$quote->addProduct($shoppingBagProduct, $request);
$quote->getShippingAddress()->setCollectShippingRates(true);
$this->quoteRepository->save($quote);
$quote->collectTotals();
}
Problem:
I checked quote_item table, product was added but all attributes related to price are 0.
quote_address_item table is fine, all prices are correct. The problem is only with quote_item.
The things I tried
$this->cart->addProduct($shoppingBagProduct, $request);
$this->cart->save();
$this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
The quote_item price will be updated, but it will redirect to Cart page again because of the following code:
/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);
}
When I try to:
setCartWasUpdated(false)
It redirects to Confirm page as I want, but the quote_item price is still 0.
System > Configuration > Sales > Checkout > After Adding a Product Redirect to Shopping Cart is set to No
Question:
I searched a lot the same problem in google but no luck to archive my goal.
May be I’m missing something here, any suggestion will be appreciated.
Thank you for reading my problem.
2
Answers
I need to set multishiping = false before add product.
as i promised to you, I’ll try to help you here this way ^^
So, first of all, you should definitly refactor you’re whole method body. You’re doing a lot of stuff more than once ^^
I can show you here an example of doing it in a magento way (untested ^^)
You may implement my custom fix for the CartItemRepository like i did it in the Github Issue.
Greetz,
Ulf