Magento – Quote id is empty when inserting multiple records into cart in magento2

addtocartajaxmagento2query

I am adding product to cart from ajax by passing product id

Here is my controller code.

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class AddItems extends \Magento\Framework\App\Action\Action
{

protected $formKey;   
protected $cart;
protected $product;
protected $_resource;
protected $checkoutSession;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Data\Form\FormKey $formKey,
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Catalog\Model\ProductFactory $product,
    \Magento\Framework\App\ResourceConnection $resource,
    \Magento\Checkout\Model\Session $checkoutSession,
    array $data = []
) {
    $this->formKey = $formKey;
    $this->cart = $cart;
    $this->product = $product;     
    $this->_resource = $resource;
    $this->checkoutSession = $checkoutSession;   
    parent::__construct($context);
}

public function execute()
{ 
   $selectedItems = $this->getRequest()->getPost('selectedItems');      
    $selectedItems = explode(",",$selectedItems);
    try{
    $connection = $this->getConnection();
    foreach ($selectedItems as $key => $selectedItem) {

        $params = array(
            'form_key' => $this->formKey->getFormKey(),
            'product_id' => $selectedItem, //product Id
            'qty'   =>1 //quantity of product                
        );
        $_product = $this->product->create()->load($selectedItem);       
         $item = $this->cart->getQuote()->getItemByProduct($_product );
        if($item){          
            $quote = $this->cart->getQuote();                   
            $quote->updateItem($item->getId(), array( 'qty' => 1));
            $quote->save();
        }else{                  
            $this->cart->addProduct($_product , $params);
        }
      $customPrice = 1000;
      $quote = $this->cart->getQuote();
      $quoteId = $quote->getId();   
      $productItem = $this->getProductQuote($_product );                
      $productItem->setCustomPrice($customPrice);
      $productItem->setOriginalCustomPrice($customPrice);
      $productItem->getProduct()->setIsSuperMode(true);     
     $insertProductSql = "INSERT INTO custom_table (quote_id, product_id) VALUES ('$quoteId', '$_product->getId()')";
        $connection->query($insertProductSql);
    }
        $this->cart->save();
        $status = 1;
    } catch (\Magento\Framework\Exception\LocalizedException $e) {
        $this->messageManager->addException($e,__('%1', $e->getMessage()));
        $status = 0;
    } catch (\Exception $e) {
        $this->messageManager->addException($e, __('error.'));
        $status = 0;
    }
    $result = array();
    $result['status'] = $status;
    $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
    $resultJson->setData($result);
    return $resultJson;
    }
   public function getConnection()
   {
    $connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
    return $connection;
    }
  public function getProductQuote($product) {
    $quote = $this->checkoutSession->getQuote();        
    $cartItems = $quote->getItemByProduct($product);        
    return $cartItems;
   }
 }

Quote id is not getting retrieved for me, always it is empty.

I need to add both the items to the cart with insert query for custom table,

products are adding to the cart successfully,but quote id storing as null inside my custom table

Note: I am setting custom price for each product.

Can anyone look into this, where i am wrong please?

Any help would be appreciated. Thanks

Best Answer

you can use same logic as magento doing for related product

if you see below file

https://github.com/magento/magento2/blob/2.3-develop/app/code/Magento/Checkout/Controller/Cart/Add.php#L105
if (!empty($related)) {
            $this->cart->addProductsByIds(explode(',', $related));
        }

if you check that model

https://github.com/magento/magento2/blob/2.3-develop/app/code/Magento/Checkout/Model/Cart.php#L419


foreach ($productIds as $productId) {
            $productId = (int)$productId;
            if (!$productId) {
                continue;
            }
            $product = $this->_getProduct($productId);
            if ($product->getId() && $product->isVisibleInCatalog()) {
                try {
                    $this->getQuote()->addProduct($product);
                } catch (\Exception $e) {
                    $allAdded = false;
                }
            } else {
                $allAvailable = false;
            }
        }

        if (!$allAvailable) {
            $this->messageManager->addError(__("We don't have some of the products you want."));
        }
        if (!$allAdded) {
            $this->messageManager->addError(__("We don't have as many of some products as you want."));
        }
    }

you need to use same logic for you.

for you:-

 $selectedItems = explode(",",$selectedItems);
foreach ($selectedItems as $key=>$selectedItem) {
    $productId = (int)$productId;
    if (!$productId) {
        continue;
    }
    $product = $this->_getProduct($selectedItem);
    if ($product->getId() && $product->isVisibleInCatalog()) {
        $this->cart->getQuote()->addProduct($product);
    } 
}

$this->cart->save();