Back to Top

Add Image to a Product Created by Installer in Magento 2

Updated 19 February 2024

Today i am explaining, if you want to created a product in Magento 2 using data patch.

Now, if you want to assign an image to that product, then you can follow the mentioned process:

Firstly you need to manage your image, i.e. you need to move your file from your module folder to media folder.

your image file should be at: /app/code/Webkul/Test/view/base/web/images/test/upload.png

Now add following code in /app/code/Webkul/Test/Setup/Patch/Data/MoveMediaFiles.php

Searching for an experienced
Magento 2 Company ?
Find out More
 <?php
namespace Webkul\Test\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Webkul\Marketplace\Model\ControllersRepository;
use Magento\Framework\App\Filesystem\DirectoryList;

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

    /**
     * Construct
     *
     * @param \Magento\Framework\Filesystem $filesystem
     * @param \Magento\Framework\Filesystem\Io\File $file
     * @param \Magento\Framework\Module\Dir\Reader $reader
     */
    public function __construct(
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\Filesystem\Io\File $file,
        \Magento\Framework\Module\Dir\Reader $reader
    ) {
        $this->filesystem = $filesystem;
        $this->file = $file;
        $this->reader = $reader;
    }

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

    /**
     * Copy Banner and Icon Images to Media
     */
    private function processDefaultImages()
    {
        $error = false;
        try {
            $this->createDirectories();
            $directory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
            $ds = "/";
            $baseModulePath = $this->reader->getModuleDir('', 'Webkul_Test');
            $mediaDetails = [
                "test" => [
                    "view/base/web/images/test" => [
                        "upload.png"
                    ]
                ] 
            ];

            foreach ($mediaDetails as $mediaDirectory => $imageDetails) {
                foreach ($imageDetails as $modulePath => $images) {
                    foreach ($images as $image) {
                        $path = $directory->getAbsolutePath($mediaDirectory);
                        $mediaFilePath = $path.$ds.$image;
                        $moduleFilePath = $baseModulePath.$ds.$modulePath.$ds.$image;

                        if ($this->file->fileExists($mediaFilePath)) {
                            continue;
                        }

                        if (!$this->file->fileExists($moduleFilePath)) {
                            continue;
                        }

                        $this->file->cp($moduleFilePath, $mediaFilePath);
                    }
                }
            }
        } catch (\Exception $e) {
            $error = true;
        }
    }

    /**
     * Create default directories
     */
    private function createDirectories()
    {
        $mediaDirectories = ['test'];
        foreach ($mediaDirectories as $mediaDirectory) {
            $directory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
            $path = $directory->getAbsolutePath($mediaDirectory);
            if (!$this->file->fileExists($path)) {
                $this->file->mkdir($path, 0777, true);
            }
        }
    }

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

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

after executing this code your file moved to pub/media/test/upload.png

Now in CreateProduct file, in which you are creating your product, add following code:

<?php

namespace Webkul\Test\Setup\Patch\Data;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

class CreateProduct implements DataPatchInterface
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $_productFactory;
    /**
     * @var \Magento\Catalog\Model\Product
     */
    protected $_productModel;
    /**
     * @var Installer
     */
    protected $_productType = \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL;
    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $_filesystem;
    protected $_objectManager;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        \Magento\Catalog\Model\Product $productModel,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\ObjectManagerInterface $objectManager
    ) {
        $this->productModel = $productModel;
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->_filesystem = $filesystem;
        $this->_objectManager = $objectManager;
    }

    
    public function apply()
    {
      $this->createProduct();
    }

    public function createProduct(){
        $appState = $this->_objectManager->get('Magento\Framework\App\State');
        $appState->setAreaCode('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',//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();
        $imagePath = $this->getViewFileUrl().'test/upload.png';
        $product->addImageToMediaGallery($imagePath, ['image', 'small_image', 'thumbnail'], false, false);
        $product->save();
    }

    public function getViewFileUrl()
    {
        return $this->_filesystem
            ->getDirectoryRead(DirectoryList::MEDIA)
            ->getAbsolutePath();
    }

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

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

After this, your product with an image is created.

I hope this blog will help you with Add Image to a Product Created 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*


Be the first to comment.

Back to Top

Message Sent!

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

Back to Home