I'd like to create simple product programmatically in magento 2. Is there any way to create ?
Magento 2 – Programmatically Create a Simple Product
magento2productprogrammatically
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
andMagento\CatalogInventory\Api\StockRegistryInterface
. The first is generated, so don't get too concerned if it shows up as not existing in your IDE.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:
You'll likely then want to add some stock for it, which you can do like this:
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: