2

I have the same problem as mentioned in this Question: Magento 2: Add multiple products to cart programmatically But it was never answered. This is my Controller.php:

<?php

namespace MassiveArt\ShoppingCart\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;

class Index extends Action
{
    /**
     * @var FormKey
     */
    protected $formKey;

    /**
     * @var Session
     */
    protected $checkoutSession;

    /**
     * @var Cart
     */
    protected $cart;

    /**
     * @var Product
     */
    protected $product;

    /**
     * Constructor.
     *
     * @param Context $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Customer\Model\Session $customerSession
     * @param JsonFactory $resultJsonFactory
     * @param FormKey $formKey
     * @param Cart $cart
     * @param Product $product
     */
    public function __construct(
        Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Customer\Model\Session $customerSession,
        JsonFactory $resultJsonFactory,
        FormKey $formKey,
        Cart $cart,
        Product $product
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->customerSession = $customerSession;
        $this->formKey = $formKey;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->cart = $cart;
        $this->product = $product;
        parent::__construct($context);
    }

    public function execute()
    {

        try {

            // Set result data and pass back
            $result = $this->resultJsonFactory->create();

            if(!$this->customerSession->getCustomer()->getId()) {
                $result->setData(['error' => __('Invalid session ID')]);
            }


            // Get parameters
            $productIds = $this->getRequest()->getParam('productIds');
            $amounts = $this->getRequest()->getParam('amounts');

            for ($i = 0; $i < count($productIds); $i++) {// Load product by ID
                $product = $this->product->load($productIds[$i]);
                // New product params
                $params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $productIds[$i],
                    'qty'   => $amounts[$i],
                );


                // Save Product
                $product->save();

                // Add product to cart
                $this->cart->addProduct($product, $params);
            }

            //Save cart
            $this->cart->save();

            $result->setData(['message' => __("Products added succesfully")]);

            return $result;
        } catch(\Exception $e) {
            $result->setData(['error' => __($e->getMessage())]);
            return $result;
        }
    }
}

The code works fine, if the cart is not empty, but if the cart is empty only one product is added to cart with sum of quantity for all the product.

For eg if I add: Prod 1 - 2 quantity Prod 2 - 1 quantity Cart will contain prod 1 with 3 quantity.

Please let me know how to solve this.

1

You're using a non-injectable object Product $product to fetch the product object and it might cause issue sometimes. Instead, we should use ProductFactory

Can you try the following snippet?

<?php

namespace MassiveArt\ShoppingCart\Controller\Index;

use Magento\Catalog\Model\ProductFactory;
use Magento\Checkout\Model\Cart;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Data\Form\FormKey;

class Index extends Action
{
    /**
     * @var FormKey
     */
    protected $formKey;

    /**
     * @var Session
     */
    protected $checkoutSession;

    /**
     * @var Cart
     */
    protected $cart;

    /**
     * @var ProductFactory
     */
    protected $productFactory;

    /**
     * Constructor.
     *
     * @param Context                         $context
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Customer\Model\Session $customerSession
     * @param JsonFactory                     $resultJsonFactory
     * @param FormKey                         $formKey
     * @param Cart                            $cart
     * @param ProductFactory                  $productFactory
     */
    public function __construct(
        Context $context,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Customer\Model\Session $customerSession,
        JsonFactory $resultJsonFactory,
        FormKey $formKey,
        Cart $cart,
        ProductFactory $productFactory
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->customerSession = $customerSession;
        $this->formKey = $formKey;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->cart = $cart;
        $this->productFactory = $productFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        try {

            // Set result data and pass back
            $result = $this->resultJsonFactory->create();

            if (!$this->customerSession->getCustomer()->getId()) {
                $result->setData(['error' => __('Invalid session ID')]);
            }

            // Get parameters
            $productIds = $this->getRequest()->getParam('productIds');
            $amounts = $this->getRequest()->getParam('amounts');

            for ($i = 0; $i < count($productIds); $i++) {// Load product by ID
                $product = $this->productFactory->create()->load($productIds[$i]);
                // New product params
                $params = [
                    'form_key' => $this->formKey->getFormKey(),
                    'product'  => $productIds[$i],
                    'qty'      => $amounts[$i],
                ];

                // Save Product
                $product->save();

                // Add product to cart
                $this->cart->addProduct($product, $params);
            }

            //Save cart
            $this->cart->save();

            $result->setData(['message' => __("Products added succesfully")]);

            return $result;
        } catch (\Exception $e) {
            $result->setData(['error' => __($e->getMessage())]);
            return $result;
        }
    }
}
  • If i copy your snippet i get a internal server error, does not seem to be working properly. Thanks for your answer – Felix Schönherr Aug 22 at 9:36
  • Did you remove the generated folder and flush the cache? What is the message in the log? – Toan Tam Aug 22 at 9:37
  • As i said I get an internal server error and not more. will try to flush the cache and remove the general folder – Felix Schönherr Aug 22 at 9:38
  • The internal error is a server error. Maybe something is wrong with the snippet since I didn't test it. Can you enable the logging report and then send me the error message? – Toan Tam Aug 22 at 9:40
  • Thank you very much, after flushing cache everything works. You are the best. – Felix Schönherr Aug 22 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.