1

How do I create a simple product programmatically using UpgradeSchema?

1

I have done with InstallData script (the same logic for UpgradeSchema script)

app/code/Vendor/Product/Setup/InstallData.php

<?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();
    }
}

A good sample here: https://github.com/magento/magento2-sample-data/blob/develop/app/code/Magento/CatalogSampleData/Model/Product.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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