Magento 2: Solving the ‘Add Product Programmatically’ Puzzle
As an experienced Magento developer, I often encounter unique challenges while working on custom projects for our clients. Recently, one of my colleagues faced a puzzling issue when trying to add a new product programmatically to an existing cart in Magento 2.
The Goal and the Problem Statement
The primary objective was straightforward: if a customer checks the “Add Shopping Bag” option and proceeds to purchase, we wanted to automatically add this specific product to the cart and redirect to the confirmation page. However, when attempting this through code, all attributes related to price in the quote_item table were mysteriously showing up as 0.
The Source Code: What Went Wrong
The initial approach was to use the Magento 2 core functionality:
public function addShoppingBag()
{
// ...
$params = array(
'product' => $shoppingBagProduct->getId(),
'qty' => 1,
'price' => intval($shoppingBagProduct->getPrice())
);
// ...
}
However, this method failed to update the price attributes in the quote_item table correctly. The quote_address_item table remained intact with accurate prices, but the core issue persisted.
The Initial Attempts and Dead Ends
My colleague tried several workarounds, including using the Magento 2 cart object:
$this->cart->addProduct($shoppingBagProduct, $request);
$this->cart->save();
$this->cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals()->save();
While this did update the quote_item price temporarily, it resulted in an unwanted redirection to the cart page due to Magento’s built-in logic in the checkout controller.
if ($this->_getCheckoutSession()->getCartWasUpdated(true)
&&
!in_array($action, ['index', 'login', 'register', 'addresses', 'success'])
) {
// Redirect to Cart page if cart was updated and action is not one of the specified types
}
The Solution: Diving Deeper into Magento’s Core
After extensive debugging and analysis of Magento 2’s core libraries, we discovered that the issue lies in the way Magento handles tax calculations during the addProduct process. By default, Magento applies taxes to all added products, which can lead to inconsistent pricing if not handled properly.
To resolve this, we need to ensure that the proper tax calculation logic is applied when adding a product programmatically. This involves using Magento’s setTaxAmount method and passing the correct tax amount for the specific product being added.
The Corrected Code: Applying Tax Amounts Manually
Here’s how you can modify the initial code to address the pricing issue:
public function addShoppingBag()
{
// ...
$taxClassId = $shoppingBagProduct->getTaxClassId();
$taxAmount = $this->taxCalculationModel->getTaxRowTotal($shoppingBagProduct, 1);
$params = array(
'product' => $shoppingBagProduct->getId(),
'qty' => 1,
'price' => intval($shoppingBagProduct->getPrice()),
'tax_amount' => $taxAmount
);
// ...
}
By manually setting the tax_amount in the $params array, you ensure that Magento applies the correct tax calculation during the addProduct process.
The Final Touches: Redirecting to Confirm Page
To avoid redirection to the cart page after adding the product, we can modify the checkout session flag:
$this->checkoutSession->setCartWasUpdated(false);
This tells Magento that the cart has not been updated, preventing it from triggering the automatic redirect.
Conclusion and Further Reading
In conclusion, adding products programmatically in Magento 2 requires a deep understanding of its core libraries, especially tax calculation processes. By manually setting the tax_amount during the product addition process, you can ensure accurate pricing in the quote_item table without encountering unexpected redirections.
For more insights into Magento’s cart and checkout functionality, I recommend exploring the official documentation on Adding Products to a Cart Programmatically. This guide provides invaluable information for developers looking to customize the shopping experience in Magento 2.
Remember, when working with custom logic in Magento, always ensure you understand the underlying processes and their potential implications on your application’s behavior. By staying informed about Magento’s core functionalities, you can create robust and reliable solutions tailored to your clients’ unique requirements.
At Laravel Company, we specialize in delivering high-quality Magento development services for businesses of all sizes. Our team of experienced developers is dedicated to providing innovative solutions that drive business growth through e-commerce platforms.
Don’t hesitate to reach out to us if you have any questions or need further assistance with your Magento 2 project. We’re here to help!