3

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.

3 Answers 3

5

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 !!

5
  • It returns "The image does not exist." error.
    – user69123
    Jul 10, 2018 at 20:10
  • Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder. Jul 10, 2018 at 20:11
  • Happy coding !! :) Jul 10, 2018 at 20:15
  • Having this error : 2 exception(s): Exception #0 (Zend_Db_Statement_Exception): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails..... Apr 19, 2019 at 10:54
  • it add video on product successfully, -1 because change position of all other images of this product.
    – HaFiz Umer
    Sep 15, 2021 at 10:43
0

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; ?>  
0

I have used Rohan solution and modify it for import video using csv

<?php
namespace CompanyName\ModuleName\Model;

use Magento\Framework\Exception\LocalizedException;

class VideoImportProcessor 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\ProductFactory $productFactory,
        \Magento\Catalog\Model\Product\Gallery\CreateHandler $createHandler
    )
    {
        parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel);
        $this->createHandler = $createHandler;
        $this->_product = $productFactory;
    }
    /**
     * @param string  $csvFile
     * @throws LocalizedException
     */
    public function importProductVideo($csvFile)
        {
            $data = [];
            foreach ($csvFile as $line) {
                $videoDataArray = str_getcsv($line);
                print_r("\n".$videoDataArray[0]);  //die;
                $productId = $videoDataArray[0]; // product id
                $product = $this->_product->create()->load($productId);
                // $product->setStoreId(1); //set store vise data

                // sample video data
                $videoData = [
                    'video_id' => "", //set your video id
                    'video_title' => $videoDataArray[2], //set your video title
                    'video_description' => $videoDataArray[3], //set your video description
                    'thumbnail' => $videoDataArray[4], //set your video thumbnail path.
                    'video_provider' => "youtube",
                    'video_metadata' => null,
                    'video_url' => $videoDataArray[1], //set your youtube video url
                    'media_type' => \Magento\ProductVideo\Model\Product\Attribute\Media\ExternalVideoEntryConverter::MEDIA_TYPE_CODE,
                    'disabled' => 0,
                ];

                //download thumbnail image and save locally under pub/media
                $videoData['file'] = $videoDataArray[4]; //$videoData['video_id'] . 'filename.jpg';

                // Add video to the product
                if ($product->hasGalleryAttribute()) {
                    $this->addVideo(
                        $product,
                        $videoData,
                        ['image', 'small_image', 'thumbnail'],
                        false,
                        true
                    );
                }
                $product->save();
            }
        }
    /**
     * @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;
    }
}

call module and pass CSV ref. using webroot PHP file CSV need data in below formate productId,video_url, video_title, video_description, thumbnail

<?php 
include('app/bootstrap.php');
use Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);


$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_GLOBAL);

$VideoImport = $objectManager->create('\CompanyName\ModuleName\Model\VideoImportProcessor');
$csvFile = file('product_video_with_product_id.csv');

print_r("\nstart_test-VideoImport");
echo $VideoImport->importProductVideo($csvFile);

print_r("\ntest_end");

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.