Magento, Magento 2

Add video to product programmatically in Magento 2

Add video to product programmatically in Magento 2

In an eCommerce store, the product page is the most important part of the whole store. There are many ways to make your product page more effectual than other eCommerce stores. A product video is one of a great way to share your product details to users and make your product page more attractive.

Magento 2 provides this feature to add product videos in an appropriate product. Sometimes, the client needs to add that video by script or API.

In this tutorial, we will learn about how to add a product video programmatically in Magento 2. First of all, let’s do the configuration for API in Magento 2.

Steps for Adding Magento 2 Product Video

For add YouTube videos to products, you need to generate a YouTube API key. For that follow this below steps.

  • Login into your Google Account and go to Google Developers Console and select your project.
  • Click on Library menu on the left corner of the page.
  • Now you will be redirected to YouTube Data API page. Click on Enable Button.
  • Go to Credential menu and copy your API key.
  • Go to the Admin Panel of your Magento 2 store and Add your API key at Store -> Configuration -> Catalog -> Catalog -> Product Video -> YouTube API Key and save config.

 

1) Create EAV module : click here

2) Simple module : click here

Steps of How to Add video to product programmatically in Magento 2 :

Firstly, Create a controller Test.php file on app/code/RH/Helloworld/Controller/Index path to add video:


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Controller\Index;

use Magento\Framework\App\Action\Action;

class Test extends Action
{

    /**
     * @var \Magento\Catalog\Model\Product
     */
    protected $_product;
    
    /**
     * @var \RH\Helloworld\Model\Product\Gallery\Video\Processor
     */
    protected $videoGalleryProcessor;


    /**
     * @param \Magento\Framework\App\Action\Context                $context
     * @param \Magento\Catalog\Model\Product                       $product
     * @param \RH\Helloworld\Model\Product\Gallery\Video\Processor $videoGalleryProcessor
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Catalog\Model\Product $product,
        \RH\Helloworld\Model\Product\Gallery\Video\Processor $videoGalleryProcessor
    ){
        parent::__construct($context);
        $this->_product = $product;
        $this->videoGalleryProcessor = $videoGalleryProcessor;
    }

    public function execute()
    {
        $productId = 1; // product id
        $product = $this->_product->load($productId);
        $product->setStoreId(0); //set store vise data

        // sample video data
        $videoData = [
            'video_id' => "abc", //set your video id
            'video_title' => "title", //set your video title
            'video_description' => "description", //set your video description
            'thumbnail' => "image path", //set your video thumbnail path.
            'video_provider' => "youtube",
            'video_metadata' => null,
            'video_url' => "https://www.youtube.com/watch?v=abc", //set your youtube channel's video url
            'media_type' => \Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter::MEDIA_TYPE_CODE,
        ];

        //download thumbnail image and save locally under pub/media
        $videoData['file'] = $videoData['video_id'] . 'filename.jpg';
        // Add video to the product
        if ($product->hasGalleryAttribute())
        {
            $this->videoGalleryProcessor->addVideo(
                $product,
                $videoData,
                ['image', 'small_image', 'thumbnail'],
                false,
                true
            );
        }
        $product->save();
    }
}

After that, create a Processor.php file to implement video processor on app/code/RH/Helloworld/Model/Product\Gallery/Video path :


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Model\Product\Gallery\Video;

use Magento\Framework\Exception\LocalizedException;

class Processor extends \Magento\Catalog\Model\Product\Gallery\Processor
{
    /**
     * @var \Magento\Catalog\Model\Product\Gallery\CreateHandler
     */
    protected $createHandler;

    /**
     * Processor constructor.
     * @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository
     * @param \Magento\MediaStorage\Helper\File\Storage\Database       $fileStorageDb
     * @param \Magento\Catalog\Model\Product\Media\Config              $mediaConfig
     * @param \Magento\Framework\Filesystem                            $filesystem
     * @param \Magento\Catalog\Model\ResourceModel\Product\Gallery     $resourceModel
     * @param \Magento\Catalog\Model\Product\Gallery\CreateHandler     $createHandler
     */
    public function __construct(
        \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository,
        \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageDb,
        \Magento\Catalog\Model\Product\Media\Config $mediaConfig,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Catalog\Model\ResourceModel\Product\Gallery $resourceModel,
        \Magento\Catalog\Model\Product\Gallery\CreateHandler $createHandler
    ) {
        parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel);
        $this->createHandler = $createHandler;
    }

    /**
     * @param \Magento\Catalog\Model\Product $product
     * @param array                          $videoData
     * @param [type]                         $mediaAttribute
     * @param boolean                        $move
     * @param boolean                        $exclude
     */
    public function addVideo(
        \Magento\Catalog\Model\Product $product,
        array $videoData,
        $mediaAttribute = null,
        $move = false,
        $exclude = true
    )
    {
        $file = $this->mediaDirectory->getRelativePath($videoData['file']);
        if (!$this->mediaDirectory->isFile($file))
        {
            throw new LocalizedException(__('The image does not exist.'));
        }

        $pathinfo = pathinfo($file);
        $imgExtensions = ['jpg', 'jpeg', 'gif', 'png'];
        if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions))
        {
            throw new LocalizedException(__('Please correct the image file type.'));
        }
        
        $fileName = \Magento\MediaStorage\Model\File\Uploader::getCorrectFileName($pathinfo['basename']);
        $dispretionPath = \Magento\MediaStorage\Model\File\Uploader::getDispretionPath($fileName);
        $fileName = $dispretionPath . '/' . $fileName;
        
        $fileName = $this->getNotDuplicatedFilename($fileName, $dispretionPath);

        $destinationFile = $this->mediaConfig->getTmpMediaPath($fileName);

        try {
            /** @var $storageHelper \Magento\MediaStorage\Helper\File\Storage\Database */
            $storageHelper = $this->fileStorageDb;
            if ($move)
            {
                $this->mediaDirectory->renameFile($file, $destinationFile);

                //Here, filesystem should be configured properly
                $storageHelper->saveFile($this->mediaConfig->getTmpMediaShortUrl($fileName));
            }
            else
            {
                $this->mediaDirectory->copyFile($file, $destinationFile);

                $storageHelper->saveFile($this->mediaConfig->getTmpMediaShortUrl($fileName));
            }
        } catch (\Exception $e) {
            throw new LocalizedException(__('We couldn\'t move this file: %1.', $e->getMessage()));
        }

        $fileName = str_replace('\\', '/', $fileName);

        $attrCode = $this->getAttribute()->getAttributeCode();
        $mediaGalleryData = $product->getData($attrCode);
        $position = 0;
        if (!is_array($mediaGalleryData))
        {
            $mediaGalleryData = ['images' => []];
        }

        foreach ($mediaGalleryData['images'] as &$image)
        {
            if (isset($image['position']) && $image['position'] > $position)
            {
                $position = $image['position'];
            }
        }

        $position++;

        unset($videoData['file']);
        $mediaGalleryData['images'][] = array_merge([
            'file' => $fileName,
            'label' => $videoData['video_title'],
            'position' => $position,
            'disabled' => (int)$exclude
        ], $videoData);

        $product->setData($attrCode, $mediaGalleryData);

        if ($mediaAttribute !== null)
        {
            $product->setMediaAttribute($product, $mediaAttribute, $fileName);
        }

        $this->createHandler->execute($product);

        return $fileName;
    }
}

After, clean cache and remove generated/generation folder.

I hope this blog is easy to understand about how to add video to product programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged , ,