1

I am new to Magento 2. I want to add items in cart programmatically. If product is found in the catalog_product_entity table then my logic is perfect & working but product is not found in the table that time i want to save the sku name, qty,price and add items in cart. Please give me suggestion.

I have written the following code:

//add items in quote
foreach($orderData['items'] as $item){

$productsku =$item['sku'];
$sql_product_entity = "Select * FROM catalog_product_entity WHERE sku ='$productsku'";
$data_product_entity = $connection->fetchAll($sql_product_entity);

if($data_product_entity){
    $product_id = $this->getProductBySku($item['sku']);
    $product = $this->_productFactory->create()->load($product_id->getEntityId());
    $product->setPrice($item['price']);
    $cart->addProduct(
                $product,
                intval($item['qty'])
            );

    }else{
        $objectManager11 = \Magento\Framework\App\ObjectManager::getInstance();
        $product11 = $objectManager11->create('Magento\Sales\Model\Order\Item');
        // $product11 = $this->productFactory->create();
        $product11->setSku($item['sku']);
        $product11->setPrice($item['price']);
        $product11->setName($item['sku']);
        $product11->setStore($store);
        $product11->setQuoteItemId(0);
        $product11->setQuoteParentItemId(NULL);
        $product11->setProductType('simple');       

        $cart->addProduct(
                $product11,
                intval($item['qty'])
        );
    }        
}

Your Answer

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

Browse other questions tagged or ask your own question.