You can create simple product programmatically using InstallData by using the below InstallData script.
<?php
namespace Vendor\Product\Setup;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
/**
* @var string
*/
protected $productType = \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE;
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $productFactory;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
public function __construct(
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager
)
{
$this->productFactory = $productFactory;
$this->storeManager = $storeManager;
}
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$data = [
'name' => 'Test',
'sku' => 'sku001',
'price' => 456,
'weight' => 1
];
$attributeSetId = 4; //Attribute set default
$product = $this->productFactory->create();
$product->setData($data);
$product
->setTypeId($this->productType)
->setAttributeSetId($attributeSetId)
->setWebsiteIds([$this->storeManager->getDefaultStoreView()->getWebsiteId()])
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(['is_in_stock' => 1, 'manage_stock' => 0, 'qty' => 100])
->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
if (empty($data['visibility'])) {
$product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
}
$product->save();
}
}Ref: http://magento.stackexchange.com/questions/166739/magento-2-how-to-create-simple-product-by-upgradeschema
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!


Leave a Reply