1

However the sample products are adding in cart,this is problem with products that has been added programmatically. Below is the code I am using to create the product programmatically.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
        $product = $objectManager->create('\Magento\Catalog\Model\Product');
        $product->setSku($productData['sku']); 
        $product->setAttributeSetId(9);
        $product->setCreatedAt(strtotime('now'));
        $product->setName($productData['productname']);
        $product->setWebsiteIds(array(1));          
        $product->setDescription($productData['productdesc']); 
        $product->setShortDescription($productData['short_description']); 
        $product->setAttributeSetId(4); 
        $product->setStatus(1); 
        $product->setWeight($productData['productweight']); 
        $product->setVisibility(4); 
        $product->setTaxClassId($productData['tax_class_id']);
        $product->setTypeId('simple'); 
        $product->setPrice($productData['price']); 
        $product->setSpecialPrice($productData['special_price']);
        $product->setSellerId($productData['sellerId']);
        $product->setCategoryIds($productData['categories']);
        $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1,
                        'is_in_stock' => $isInStock,
                        'qty' => $quantity
                    )
                );

        $product->save();   </i>
  • Please check var\log for error – Ankit Shah Jan 3 '17 at 10:22
  • You have passed setAttributeSetId 2 times. remove it one. – Bojjaiah Jan 4 '17 at 5:31
  • Yes I have removed one but the issue still persist. – Ranjeet Singh Jan 4 '17 at 7:59
  • @AnkitShah Nothing is coming in error log – Ranjeet Singh Jan 4 '17 at 8:36
  • HI guys! this is solved, actually there is an observer which called with add cart process and there is some error in it.That is why it was not working. Thanks!! – Ranjeet Singh Feb 7 '17 at 7:25
0

This below code will create a product with -sample sku of existing SKU and add product to the cart.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$product = $objectManager->create('Magento\Catalog\Model\Product');
        try {
            $product->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
                    ->setAttributeSetId(4) //ID of a attribute set named 'default'
                    ->setTypeId('simple') 
                    ->setCreatedAt(strtotime('now')) 
                    ->setSku('sam'.$sku) //SKU
                    ->setName($name."-sample")
                    ->setWeight(4.0000)
                    ->setCategoryIds(7)
                    ->setStatus(1) 
                    ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
                    ->setVisibility(1) 
                    ->setPrice(0.99) 
                    ->setMetaTitle($prod->getMetaTitle())
                    ->setMetaKeyword($prod->getMetaKeyword())
                    ->setMetaDescription($prod->getMetaDescription())
                    ->setDescription($prod->getDescription())
                    ->setShortDescription($prod->getShortDescription())
                    ->setMediaGallery (array('images'=>array (), 'values'=>array ())) 
                    ->addImageToMediaGallery($imageUrl, array('image','thumbnail','small_image'), false, false)
                    ->setStockData(
                        array(
                           'use_config_manage_stock' => 0, //'Use config settings' checkbox
                           'manage_stock'=>1, //manage stock
                           'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
                           'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
                           'is_in_stock' => 1, //Stock Availability
                           'qty' => 99999 //qty
                        )
                    );

                //echo "BEFORE SAVING THE NEW PRODUCT";
                $res = $product->save();
                //echo "AFTER SAVING THE NEW PRODUCT";

                //var_dump($res); 
                $ids=$product->getEntityId();
                // Save the new Sample Product ID to original product Attribute. 
            } catch (Exception $e ) {
                echo    $e->getMessage();
            }
        $cart = $objectManager->get('Magento\Checkout\Model\Cart');
        $productRepo = $objectManager->get('Magento\Catalog\Model\ProductRepository');
        $pId=$product->getId();
        $productData = [];
        $productData['qty'] = 1; 
        $productData['product'] = $pId; 

        $_addproduct = $productRepo->getById($pId);
        if ($_addproduct) {
            $cart->addProduct($_addproduct, $productData); // adds product in cart using cart model
        }
        $cart->save();
        $cart->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
        $cart->getQuote()->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.