Question

I am new in magento. I saw some links about add video programmatically, but I didn't get output which is working perfect.

How to add product video programmatically to the specific product ?

Please guide me.

Thanks.

Was it helpful?

Solution

Reference : Click here

=> Follow the step to create video :

Create a controller Test.php file on this below path :

CompanyName\ModuleName\Controller\Index

<?php
namespace CompanyName\ModuleName\Controller\Index;

use Magento\Framework\App\Action\Action;

class Test extends Action
{
    protected $videoGalleryProcessor;
    protected $_product;
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Catalog\Model\Product $product,
        \CompanyName\ModuleName\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 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();
    }
}

Then, create a Processor.php file to implement video processor on this below path :

<?php
namespace CompanyName\ModuleName\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 array $mediaAttribute
     * @param bool $move
     * @param bool $exclude
     * @return string
     * @throws LocalizedException
     */
    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;
    }
}

Clean cache and run it. Hope this will helpful for you !!

OTHER TIPS

If Displaying video in product page using mp4 video or another types of video

We have to create attribute to add video name

Then get this video name to where you want to display video

Import videos in video folder in 'pub/media/catalog/product/videos/'

<?php
    $_helper = $this->helper('Magento\Catalog\Helper\Output');
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
?>

<?php if($proVideo = $_helper->productAttribute($_product,$_product->getVideoName(), 'video_name')):?>
    <?php $videoUrl = $this->getUrl('pub/media/catalog/product/videos/').$proVideo; ?>
    <div class="prod_video_bg">
        <video width="400" controls>
          <source src="<?php echo $videoUrl; ?>" type="video/mp4">
        </video>
    </div>
<?php endif; ?>  
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top