Request Quote

Add image to a product created by installer in magento2

Today i am explaining, if you want to created a product in magento2 using installer then you can follow following link:

Create Product By Installer

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/frontend/web/images/upload.png

Now add following code in /app/code/Webkul/Test/Setup/InstallSchema.php

<?php
namespace Webkul\Test\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class InstallSchema implements InstallSchemaInterface
{
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $this->moveDirToMediaDir();
        //rest code of installer
    }
    /**
     * moveDirToMediaDir move directories to media
     * @return void
     */
    private function moveDirToMediaDir()
    {
        try {
            $objManager = \Magento\Framework\App\ObjectManager::getInstance();
            $reader = $objManager->get('Magento\Framework\Module\Dir\Reader');
            $filesystem = $objManager->get('Magento\Framework\Filesystem');
            $type = \Magento\Framework\App\Filesystem\DirectoryList::MEDIA;
            $smpleFilePath = $filesystem->getDirectoryRead($type)
                ->getAbsolutePath().'test/';
            
            $modulePath = $reader->getModuleDir('', 'Webkul_test');
            $mediaFile = $modulePath.'/view/frontend/web/images/upload.png';
            if (!file_exists($smpleFilePath)) {
                mkdir($smpleFilePath, 0777, true);
            }

            $filePath = $smpleFilePath.'upload.png';
            if (!file_exists($filePath)) {
                if (file_exists($mediaFile)) {
                    copy($mediaFile, $filePath);
                }
            }
        } catch (\Exception $e) {
            /*error*/
        }
    }
}

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

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

namespace Webkul\Test\Setup;

use Magento\Framework\Setup;
use Magento\Framework\App\Filesystem\DirectoryList;

class InstallData implements Setup\InstallDataInterface
{
    /**
     * @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 \Magento\Catalog\Model\Product                $productModel
     * @param \Magento\Store\Model\StoreManagerInterface    $storeManager
     * @param \Magento\Catalog\Model\ProductFactory         $productFactory
     * @param \Magento\Framework\Filesystem                 $filesystem
     */
    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 install(
        Setup\ModuleDataSetupInterface $setup,
        Setup\ModuleContextInterface $moduleContext
    ) {
        $appState = $this->_objectManager->get('Magento\Framework\App\State');
        $appState->setAreaCode('adminmhtml');
        $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($this->productType);
        $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();
    }
}

After this, your product with an image is created.

Hope this blog is helps you.

Thank you.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php