4

I have created a custom module and add multiple products in cart on Ajax request. I follow a default Magento code for adding product to cart. But every time Magento throws below error.

Cart %1 does not contain item %2

This error is throws from

vendor/magento/module-quote/Model/Quote/Item/CartItemPersister.php

I have debugged Magento code and found that it creates new quote every time and it only occurs when the customer is not logged in.

When a customer is logged in its working fine.

  • please share code from your module – Claudiu Creanga Jul 7 '16 at 21:13
  • Try CSRF, its working for me. Make sure your security also. – zus Dec 25 '17 at 7:48
1

I found this to be an issue with using: \Magento\Quote\Model\QuoteFactory and \Magento\Quote\Model\QuoteManagement whilst creating my order. I resolved this by using the CartRepositoryInterface and CartManagementInterface instead.

I encountered this problem attempting to programmatically create an order. You may be able to engineer a solution based on my code as I imagine at it's root, it's the same issue.

Blog post here: http://frankclark.xyz/magento2-1-programatically-create-order

  • Please post your solution here instead of linking to another website. – 7ochem Aug 11 '16 at 8:22
  • Well the question doesn't have a code example for me to change. So i'm not going to write an entire class to answer this question. The gist of it is that if you are using the QuoteManager and Factory, don't. Use the Cart Manager instead. Magento did an update in 2.1 that completely requires you to do it this way. – Frank Aug 12 '16 at 15:22
1

I created custom module to add to cart multiple product , you need to make action for this controller when click on add to cart with custom template for list or view whatever.

namespace Vender\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
          * @var \Magento\Checkout\Model\Cart
          */
         protected $cart;
         /**
          * @var \Magento\Catalog\Model\Product
          */
         protected $product;

         protected $_checkoutSession;

         public function __construct(
             \Magento\Framework\App\Action\Context $context,
             \Magento\Framework\View\Result\PageFactory $resultPageFactory,
             \Magento\Catalog\Model\Product $product,
             \Magento\Checkout\Model\Cart $cart,
             \Magento\Checkout\Model\Session $checkoutSession
         ) {
             $this->resultPageFactory = $resultPageFactory;
             $this->cart = $cart;
             $this->product = $product;
             $this->_checkoutSession = $checkoutSession;
             parent::__construct($context);
         }

    public function execute()
         {

            $post  = $this->getRequest()->getParams();
             try {

                        foreach($post['qty'] as $key=>$value){
                           if($value[0]>0){
                           //echo $key.'---'.$value[0];
                             $_product = $this->product->load($key);

                             if ($_product) {
                                 $this->cart->addProduct($key, array('qty' =>$value[0]));

                                }
                          }
                       }
              $this->cart->save();         

              $this->messageManager->addSuccess(__(' Add to cart successfully.'));   
             }
              catch (\Magento\Framework\Exception\LocalizedException $e) {
                 $this->messageManager->addException(
                     $e,
                     __('%1', $e->getMessage())
                 );
             } catch (\Exception $e) {
                 $this->messageManager->addException($e, __('.error'));
             }
             /*cart page*/
             $cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl();
             $this->getResponse()->setRedirect($cartUrl);
         }
    }
?>
1

Please check it

<?php
namespace Company\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Catalog\Model\Product\Type;


class CheckoutCartProductAddAfter implements ObserverInterface
{   

    protected $_cart;

    public function __construct(
    \Magento\Checkout\Model\Cart $cart, 
    \Magento\Framework\App\RequestInterface $request
    ){      
        $this->_cart = $cart;
        $this->_request = $request;    
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {

        if(!empty($this->_request->getParam('pids'))){ //product ids array

            $product_ids = $this->_request->getParam('pids'); //product ids array           
            $this->_cart->addProductsByIds($product_ids);   // it's work only simple product        
            $this->_cart->save();       

        }       
        return $this;

    }
}

?>

OR

<?php
namespace Company\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Catalog\Model\Product\Type;


class CheckoutCartProductAddAfter implements ObserverInterface
{   

    protected $_productRepository;
    protected $_cart;
    protected $formKey;

    public function __construct(
    \Magento\Catalog\Model\ProductRepository $productRepository, 
    \Magento\Checkout\Model\Cart $cart, 
    \Magento\Framework\App\RequestInterface $request,
    \Magento\Framework\Data\Form\FormKey $formKey
    ){
        $this->_productRepository = $productRepository;
        $this->_cart = $cart;
        $this->_request = $request;
        $this->formKey = $formKey;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $item = $observer->getEvent()->getData('quote_item');
        $product = $observer->getEvent()->getData('product');
        $item = ($item->getParentItem() ? $item->getParentItem() : $item);



        if(!empty($this->_request->getParam('pids'))){
            $product_ids = $this->_request->getParam('pids'); //product ids array 

            foreach($product_ids as $product_id){

                $_product = $this->_productRepository->getById($product_id);

                if($product->getId() != $product_id){
                    $params = array(
                        'product' => $product_id,
                        'qty' => 1,
                    );

                    $this->_cart->getQuote()->addProduct($_product);                    
                }               

            }           
            $this->_cart->save();           
        }       
        return $this;       
    }
}
?>
0

Try solution below

foreach($productArray as $id => $qty)
{
    $params = array(
        'product' => $id,
        'qty' => $qty
    );
    $product = \Magento\Framework\App\ObjectManager::getInstance()->create('\Magento\Catalog\Model\ProductRepository')->getById($id);
    try {
        if($this->cart->addProduct($product,$params)){$success[] = "success";}
    } catch (\Exception $e) {
        $this->messageManager->addError($this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage()));
    }
}
$this->cart->save();

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.