You can create simple product programmatically using InstallData by using the below InstallData script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | <?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 Team HiddenTechiesWrite an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!
Recent Comments