1

I am trying to create product programmatically with code. Product is successfully created but without quantity. How can add quantity.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
                $product = $objectManager->create('\Magento\Catalog\Model\Product');
                $product->setSku('conf5'); // Set your sku here
                $product->setName('conf5'); // Name of Product
                $product->setAttributeSetId(9); // Attribute set id
                $product->setStatus(1); // Status on product enabled/ disabled 1/0
                $product->setWeight(10); // weight of product
                $product->setWebsiteIds(array(1));
                $product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
                $product->setTaxClassId(3); // Tax class id
                $product->setTypeId('configurable'); // type of product (simple/virtual/downloadable/configurable)
                $product->setDescription('descript');
                $product->setShortDescription('shortdes');
                $product->setPrice(100);*/ // price of product
                $product->setStockData(
                    array(
                        'use_config_manage_stock' => 0,
                        'manage_stock' => 1,
                        'is_in_stock' => 1,
                        'qty' => 9
                    )
                );
1

2 Answers 2

0

I usually do the following in my data fixtures:

/** @var \Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem */
$stockItem = $objectManager->create(\Magento\CatalogInventory\Api\Data\StockItemInterface::class);
$stockItem->setQty(100)->setIsInStock(true);
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setStockItem($stockItem);

/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productRepository->save($product);
1
  • I had tried this but still quantity not update.
    – Anees
    Commented Feb 22, 2019 at 11:12
0

This solve my issue
$product->setQuantityAndStockStatus(['qty' => 23, 'is_in_stock' => 1]);

Your Answer

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

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