I've read some other post about adding products to cart, but nothing seems to fit.
I've an observer for checkout_cart_update_items_before
that adds another product in same qty if specific product is added.
So quantity for product A and B should always be same.
Observer:
public function execute(Observer $observer): void
{
/** @var \Magento\Framework\DataObject $info */
$info = $observer->getInfo();
/* @var \Magento\Quote\Model\Quote $quote */
$quote = $observer->getCart()->getQuote();
$cartItems = $quote->getAllItems();
$update = false;
$newQty = 0;
foreach ($cartItems as $item) {
if ($this->helper->isDepositProduct($item->getProduct())) {
$newQty += $info[$item->getId()]['qty'];
$item->setQty($info[$item->getId()]['qty']);
$update = true;
}
}
if ($update) {
$addItem = $this->helper->getDepositProduct();
if ($addItem && $addItem->getId()) {
$addQuoteItem = $quote->getItemByProduct($addItem);
if ($addQuoteItem) {
if ($newQty <= 0) {
$quote->removeItem($addQuoteItem->getId());
$quote->save();
} else {
$addQuoteItem->setQty($newQty);
$observer->getCart()->save();
}
}
}
}
}
Works:
Luma theme ... update from mini-cart popup works.
Doesn't Works:
- update quantity in cart
- update quantity in "product options" edit (pen icon in cart/popup)
It only updates qty count next to cart icon in header, but totals and qty input fields do not get changed on the cart page.
This code was ported from M1 and worked there w/o problems :(. So, what is the difference between updating via mini-cart-popup and in checkout cart?
Is there any problems with $observer->getCart()->save();
?