Back to Top

Create a Product by Data Patch File in Magento 2

Updated 23 February 2024

Magento-Code-Snippet-5-3

To create a product by using the Data Patch file you need to add the file “CreateProduct.php” at path:

app/code/Webkul/Hello/Setup/Patch/Data/CreateProduct.php

<?php

namespace Webkul\Test\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

class CreateProduct implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface $moduleDataSetup
     */
    private $moduleDataSetup;


    public function __construct(
        \Magento\Catalog\Model\Product $productModel,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->productModel = $productModel;
        $this->storeManager = $storeManager;
        $this->_objectManager = $objectManager;
        $this->productFactory = $productFactory;
    }

    /**
     * Do Upgrade
     *
     * @return void
     */
    public function apply()
    {
        $this->createProduct();
    }

    
    private function createProduct()
    {
        $appState = $this->_objectManager->get('Magento\Framework\App\State');
        $appState->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
        $product = $this->productFactory->create();
        $attributeSetId = $this->productModel->getDefaultAttributeSetId();
        $product->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID); 
        $product->setWebsiteIds([$this->storeManager->getDefaultStoreView()->getWebsiteId()]);
        $product->setTypeId('simple');
        $product->addData(array(
            'name' => 'Sample product Test',//name of product
            'attribute_set_id' => $attributeSetId,
            'status' => \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED, 
            'visibility' => \Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE, 
            'weight' => 1,
            'sku' => 'sample_product',//SKU of product
            'tax_class_id' => 0,
            'description' => 'sample_product',
            'short_description' => 'sample_product',
            'stock_data' => array( //stock management
                'manage_stock' => 1,
                'qty' => 999, 
                'is_in_stock' => 1
            )
        ));
        $product->save();
    }


    /**
     * Get aliases
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * Get dependencies
     */
    public static function getDependencies()
    {
        return [];
    }
}

Here,

$this->productModel->getDefaultAttributeSetId(): used to get get default attribute set id

\Magento\Catalog\Model\Product\Visibility: used to get visibility of product

Searching for an experienced
Magento 2 Company ?
Find out More

\Magento\Catalog\Model\Product\Attribute\Source\Status: used to get the status of the product

$this->storeManager->getDefaultStoreView()->getWebsiteId(): used to get website id.

\Magento\Store\Model\Store: used to get store id

\Magento\Framework\App\Area::AREA_ADMINHTML: used to set “admin” as an area code.

After that, you just need to run the upgrade command, and your product is created in your site.

Upgrade command: php bin/magento setup:upgrade

I hope this blog will help you with creating a Product by Installer in Magento 2. You may also check our wide range of best Magento 2 Extensions.

Please reach out to our team via a support ticket if you have any queries.

Try this and if you have any queries then just comment below 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


1 comments

  • Anil
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home