1

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

11
  • print your sql query (echo $insertProductSql ) in browser and then check if you are getting the quote id in your insert query or not. May 13, 2019 at 12:00
  • @DineshYadav, not its not returned quoteid after printing it. May 13, 2019 at 12:16
  • Paste your query here which you printed in the browser. May 13, 2019 at 12:22
  • @DineshYadav, here is my result, INSERT INTO custom_table (quote_id, product_id) VALUES ('','3') May 13, 2019 at 12:25
  • Have you tried this? $this->cart->save(); $quote = $this->cart->getQuote(); $quoteId = $quote->getId(); May 13, 2019 at 12:30

4 Answers 4

2

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();
11
  • hi @Sunil Patel, is it possible to update for my question, that will be more helpful May 14, 2019 at 7:38
  • @jafarpinjar updated answer. May 14, 2019 at 7:47
  • what is $this->getQuote() here? need to inject any class?, then i am setting custom price for each item, May 14, 2019 at 7:50
  • @jafarpinjar updated May 14, 2019 at 7:56
  • hi @Sunil, so i need to replace only this line, $this->cart->addProduct($_product , $params); to $this->cart->getQuote()->addProduct($_product ,$params) May 14, 2019 at 8:00
0

I think you need to save the quote after adding product into the cart.

  $quote = $this->cart->getQuote();

after this line you can save the quote $quote->save(); then you can get the $quote->getId()

8
  • hi @Keyur shaw, no if used that code, two products will not add to cart May 10, 2019 at 13:42
  • What If you use $this->cart->save(); after $this->cart->addProduct as Magento is also using the same @jafarpinjar
    – Keyur Shah
    May 10, 2019 at 13:44
  • shaw, did you try the code, if used like that two products will not add to the cart May 10, 2019 at 13:50
  • because, i am setting custom price for each product, cart->save() used inside for each means, price for second product getting as 0 May 10, 2019 at 14:02
  • price 0 means? you are getting quote id or not?
    – Keyur Shah
    May 10, 2019 at 15:14
0

Try with this function:

public function execute()
{
    $selectedItems = $this->getRequest()->getPost('selectedItems');
    $selectedItems = explode(",", $selectedItems);
    try {

        $this->cart->save();
        $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) {
                $this->cart->updateItem($item->getId(), array('qty' => 1));
            } 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;
}
3
  • @Daneil, yes tried it, if $this->cart->save(); is used inside foreach, the custom price for next product is set to 0, that is why i used save() outside for each. May 14, 2019 at 7:17
  • I have just updated the answer, please try again May 14, 2019 at 8:35
  • this is adding only one product to the cart, not both Jun 21, 2019 at 6:07
0

Don't forget about clone configurable product object when pass it to addProduct method

$this->_cart->addProduct(clone $product, $params);

It helps to add few simple products of one configurable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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