Magento 2 – Programmatically Create a Simple Product

magento2productprogrammatically

I'd like to create simple product programmatically in magento 2. Is there any way to create ?

Best Answer

First, in your constructor you'll want to include three classes for dependency injection: Magento\Catalog\Api\Data\ProductInterfaceFactory, Magento\Catalog\Api\ProductRepositoryInterface and Magento\CatalogInventory\Api\StockRegistryInterface. The first is generated, so don't get too concerned if it shows up as not existing in your IDE.

public function __construct(\Magento\Catalog\Api\Data\ProductInterfaceFactory $productFactory, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry)
{
    $this->productFactory = $productFactory;
    $this->productRepository = $productRepository;
    $this->stockRegistry = $stockRegistry;
}

From there, where you want to create the product, you'll need to use the Factory to create it and set the data, and the repository to save it:

/** @var \Magento\Catalog\Api\Data\ProductInterface $product */
$product = $this->productFactory->create();
$product->setSku('SAMPLE-ITEM');
$product->setName('Sample Item');
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);
$product->setVisibility(4);
$product->setPrice(1);
$product->setAttributeSetId(4); // Default attribute set for products
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
// If desired, you can set a tax class like so:
$product->setCustomAttribute('tax_class_id', $taxClassId);

$product = $this->productRepository->save($product); // This is important - the version provided and the version returned will be different objects

You'll likely then want to add some stock for it, which you can do like this:

$stockItem = $this->stockRegistry->getStockItemBySku($product->getSku());
$stockItem->setIsInStock($isInStock);
$stockItem->setQty($stockQty);
$this->stockRegistry->updateStockItemBySku($product->getSku(), $stockItem);

If you're running this in a script (including setup/upgrade scripts), then you're also going to need to emulate the area as this sort of thing requires sessions for some crazy reason.

To do that, pull in \Magento\Framework\App\State through the constructor, and then utilize this code:

$this->state->emulateAreaCode(
    'adminhtml', 
    function () { 
        /* all code here */ 
    }
);
Related Topic