How to Add New Product Programmatically to Existing Cart in Magento 2

Mar 19, 20191546
How to Add New Product Programmatically to Existing Cart in Magento 2

In this article we will address the issue that is widely discussed at the Magento 2 thematic forums — when you add a product to the user’s cart programmatically, the cost of the product becomes zero. To solve this problem, we have created a module that provides a convenient interface for adding items to the selected basket.

Install the test instance Magento 2.3.0 with sample data.

At the end of the article you will find the code of the developed module. The module creates a page in the Magento administration panel with an interface for adding items to the cart with an indication of the SKU (if necessary) and quantity. The action to add goods to the basket is performed in the action Index. Bear in mind there still can be difficulties with the use of different types of goods (Simple, Virtual, Configurable, Downloadable, Bundle, Grouped), because for certain the parameter of the addProduct function of the Quote object should be formed in a special way.

add to cart

add to cart 2

Having tested all variations of types of goods, we found no problems with the price. Therefore, we conclude that this problem is not connected with the standard delivery of Magento 2.3.0, but rather lies in mistakes in the code or a conflict with a third-party module. Ideally, each case when a problem with the price during the programmatic addition of goods to the basket is individual and must be considered separately to determine and eliminate an underlying cause.

Module code is available on GitHub: https://github.com/belvg-public/AddToCart

Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Igor

app/code/BelVG/AddToCart/registration.php

app/code/BelVG/AddToCart/etc/module.xml

app/code/BelVG/AddToCart/etc/acl.xml

app/code/BelVG/AddToCart/etc/adminhtml/routes.xml

app/code/BelVG/AddToCart/etc/adminhtml/menu.xml

app/code/BelVG/AddToCart/Block/AddToCart.php

app/code/BelVG/AddToCart/Controller/Adminhtml/Index/Index.php

app/code/BelVG/AddToCart/Controller/Adminhtml/Index/Options.php

app/code/BelVG/AddToCart/view/adminhtml/layout/belvg_addtocart_index_index.xml

Summary

This is how you solve the problem with adding new product programmatically to existing Cart in Magento 2. If you have any questions or comments, feel free to leave them in the comments.


Partner With Us Looking for a partner to grow your business? We are the right company to bring your webstore to success. Talk to Igor

1 comment

  1. Hello,

    A great guide. Yes, this is one of the common issues that occur when products added to the cart pragmatically.

    Thanks for providing a comprehensive solution!

Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *