Magento 2.2.5 : Add video to product programmatically
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.
product-video magento-2.2.5
add a comment |
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.
product-video magento-2.2.5
add a comment |
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.
product-video magento-2.2.5
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.
product-video magento-2.2.5
product-video magento-2.2.5
asked Jul 10 '18 at 19:52
user69123
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
=> Follow the step to create video :
Create a controller Test.php file on this below path :
CompanyNameModuleNameControllerIndex
<?php
namespace CompanyNameModuleNameControllerIndex;
use MagentoFrameworkAppActionAction;
class Test extends Action
{
protected $videoGalleryProcessor;
protected $_product;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoCatalogModelProduct $product,
CompanyNameModuleNameModelProductGalleryVideoProcessor $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' => MagentoProductVideoModelProductAttributeMediaExternalVideoEntryConverter::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 CompanyNameModuleNameModelProductGalleryVideo;
use MagentoFrameworkExceptionLocalizedException;
class Processor extends MagentoCatalogModelProductGalleryProcessor
{
/**
* @var MagentoCatalogModelProductGalleryCreateHandler
*/
protected $createHandler;
/**
* Processor constructor.
* @param MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository
* @param MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb
* @param MagentoCatalogModelProductMediaConfig $mediaConfig
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoCatalogModelResourceModelProductGallery $resourceModel
* @param MagentoCatalogModelProductGalleryCreateHandler $createHandler
*/
public function __construct(
MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository,
MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb,
MagentoCatalogModelProductMediaConfig $mediaConfig,
MagentoFrameworkFilesystem $filesystem,
MagentoCatalogModelResourceModelProductGallery $resourceModel,
MagentoCatalogModelProductGalleryCreateHandler $createHandler
)
{
parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel);
$this->createHandler = $createHandler;
}
/**
* @param MagentoCatalogModelProduct $product
* @param array $videoData
* @param array $mediaAttribute
* @param bool $move
* @param bool $exclude
* @return string
* @throws LocalizedException
*/
public function addVideo(
MagentoCatalogModelProduct $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 = MagentoMediaStorageModelFileUploader::getCorrectFileName($pathinfo['basename']);
$dispretionPath = MagentoMediaStorageModelFileUploader::getDispretionPath($fileName);
$fileName = $dispretionPath . '/' . $fileName;
$fileName = $this->getNotDuplicatedFilename($fileName, $dispretionPath);
$destinationFile = $this->mediaConfig->getTmpMediaPath($fileName);
try {
/** @var $storageHelper MagentoMediaStorageHelperFileStorageDatabase */
$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 !!
It returns "The image does not exist." error.
– user69123
Jul 10 '18 at 20:10
Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder.
– Rohan Hapani
Jul 10 '18 at 20:11
Happy coding !! :)
– Rohan Hapani
Jul 10 '18 at 20:15
add a comment |
If Display video in product page using mp4 video and another types of video
We have to need create attribute for add video name
Then get this video name to where want to display video
Import videos in video folder in 'pub/media/catalog/product/videos/'
<?php
$_helper = $this->helper('MagentoCatalogHelperOutput');
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$_product = $objectManager->get('MagentoFrameworkRegistry')->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; ?>
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f233057%2fmagento-2-2-5-add-video-to-product-programmatically%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
=> Follow the step to create video :
Create a controller Test.php file on this below path :
CompanyNameModuleNameControllerIndex
<?php
namespace CompanyNameModuleNameControllerIndex;
use MagentoFrameworkAppActionAction;
class Test extends Action
{
protected $videoGalleryProcessor;
protected $_product;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoCatalogModelProduct $product,
CompanyNameModuleNameModelProductGalleryVideoProcessor $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' => MagentoProductVideoModelProductAttributeMediaExternalVideoEntryConverter::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 CompanyNameModuleNameModelProductGalleryVideo;
use MagentoFrameworkExceptionLocalizedException;
class Processor extends MagentoCatalogModelProductGalleryProcessor
{
/**
* @var MagentoCatalogModelProductGalleryCreateHandler
*/
protected $createHandler;
/**
* Processor constructor.
* @param MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository
* @param MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb
* @param MagentoCatalogModelProductMediaConfig $mediaConfig
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoCatalogModelResourceModelProductGallery $resourceModel
* @param MagentoCatalogModelProductGalleryCreateHandler $createHandler
*/
public function __construct(
MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository,
MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb,
MagentoCatalogModelProductMediaConfig $mediaConfig,
MagentoFrameworkFilesystem $filesystem,
MagentoCatalogModelResourceModelProductGallery $resourceModel,
MagentoCatalogModelProductGalleryCreateHandler $createHandler
)
{
parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel);
$this->createHandler = $createHandler;
}
/**
* @param MagentoCatalogModelProduct $product
* @param array $videoData
* @param array $mediaAttribute
* @param bool $move
* @param bool $exclude
* @return string
* @throws LocalizedException
*/
public function addVideo(
MagentoCatalogModelProduct $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 = MagentoMediaStorageModelFileUploader::getCorrectFileName($pathinfo['basename']);
$dispretionPath = MagentoMediaStorageModelFileUploader::getDispretionPath($fileName);
$fileName = $dispretionPath . '/' . $fileName;
$fileName = $this->getNotDuplicatedFilename($fileName, $dispretionPath);
$destinationFile = $this->mediaConfig->getTmpMediaPath($fileName);
try {
/** @var $storageHelper MagentoMediaStorageHelperFileStorageDatabase */
$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 !!
It returns "The image does not exist." error.
– user69123
Jul 10 '18 at 20:10
Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder.
– Rohan Hapani
Jul 10 '18 at 20:11
Happy coding !! :)
– Rohan Hapani
Jul 10 '18 at 20:15
add a comment |
=> Follow the step to create video :
Create a controller Test.php file on this below path :
CompanyNameModuleNameControllerIndex
<?php
namespace CompanyNameModuleNameControllerIndex;
use MagentoFrameworkAppActionAction;
class Test extends Action
{
protected $videoGalleryProcessor;
protected $_product;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoCatalogModelProduct $product,
CompanyNameModuleNameModelProductGalleryVideoProcessor $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' => MagentoProductVideoModelProductAttributeMediaExternalVideoEntryConverter::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 CompanyNameModuleNameModelProductGalleryVideo;
use MagentoFrameworkExceptionLocalizedException;
class Processor extends MagentoCatalogModelProductGalleryProcessor
{
/**
* @var MagentoCatalogModelProductGalleryCreateHandler
*/
protected $createHandler;
/**
* Processor constructor.
* @param MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository
* @param MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb
* @param MagentoCatalogModelProductMediaConfig $mediaConfig
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoCatalogModelResourceModelProductGallery $resourceModel
* @param MagentoCatalogModelProductGalleryCreateHandler $createHandler
*/
public function __construct(
MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository,
MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb,
MagentoCatalogModelProductMediaConfig $mediaConfig,
MagentoFrameworkFilesystem $filesystem,
MagentoCatalogModelResourceModelProductGallery $resourceModel,
MagentoCatalogModelProductGalleryCreateHandler $createHandler
)
{
parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel);
$this->createHandler = $createHandler;
}
/**
* @param MagentoCatalogModelProduct $product
* @param array $videoData
* @param array $mediaAttribute
* @param bool $move
* @param bool $exclude
* @return string
* @throws LocalizedException
*/
public function addVideo(
MagentoCatalogModelProduct $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 = MagentoMediaStorageModelFileUploader::getCorrectFileName($pathinfo['basename']);
$dispretionPath = MagentoMediaStorageModelFileUploader::getDispretionPath($fileName);
$fileName = $dispretionPath . '/' . $fileName;
$fileName = $this->getNotDuplicatedFilename($fileName, $dispretionPath);
$destinationFile = $this->mediaConfig->getTmpMediaPath($fileName);
try {
/** @var $storageHelper MagentoMediaStorageHelperFileStorageDatabase */
$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 !!
It returns "The image does not exist." error.
– user69123
Jul 10 '18 at 20:10
Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder.
– Rohan Hapani
Jul 10 '18 at 20:11
Happy coding !! :)
– Rohan Hapani
Jul 10 '18 at 20:15
add a comment |
=> Follow the step to create video :
Create a controller Test.php file on this below path :
CompanyNameModuleNameControllerIndex
<?php
namespace CompanyNameModuleNameControllerIndex;
use MagentoFrameworkAppActionAction;
class Test extends Action
{
protected $videoGalleryProcessor;
protected $_product;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoCatalogModelProduct $product,
CompanyNameModuleNameModelProductGalleryVideoProcessor $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' => MagentoProductVideoModelProductAttributeMediaExternalVideoEntryConverter::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 CompanyNameModuleNameModelProductGalleryVideo;
use MagentoFrameworkExceptionLocalizedException;
class Processor extends MagentoCatalogModelProductGalleryProcessor
{
/**
* @var MagentoCatalogModelProductGalleryCreateHandler
*/
protected $createHandler;
/**
* Processor constructor.
* @param MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository
* @param MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb
* @param MagentoCatalogModelProductMediaConfig $mediaConfig
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoCatalogModelResourceModelProductGallery $resourceModel
* @param MagentoCatalogModelProductGalleryCreateHandler $createHandler
*/
public function __construct(
MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository,
MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb,
MagentoCatalogModelProductMediaConfig $mediaConfig,
MagentoFrameworkFilesystem $filesystem,
MagentoCatalogModelResourceModelProductGallery $resourceModel,
MagentoCatalogModelProductGalleryCreateHandler $createHandler
)
{
parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel);
$this->createHandler = $createHandler;
}
/**
* @param MagentoCatalogModelProduct $product
* @param array $videoData
* @param array $mediaAttribute
* @param bool $move
* @param bool $exclude
* @return string
* @throws LocalizedException
*/
public function addVideo(
MagentoCatalogModelProduct $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 = MagentoMediaStorageModelFileUploader::getCorrectFileName($pathinfo['basename']);
$dispretionPath = MagentoMediaStorageModelFileUploader::getDispretionPath($fileName);
$fileName = $dispretionPath . '/' . $fileName;
$fileName = $this->getNotDuplicatedFilename($fileName, $dispretionPath);
$destinationFile = $this->mediaConfig->getTmpMediaPath($fileName);
try {
/** @var $storageHelper MagentoMediaStorageHelperFileStorageDatabase */
$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 !!
=> Follow the step to create video :
Create a controller Test.php file on this below path :
CompanyNameModuleNameControllerIndex
<?php
namespace CompanyNameModuleNameControllerIndex;
use MagentoFrameworkAppActionAction;
class Test extends Action
{
protected $videoGalleryProcessor;
protected $_product;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoCatalogModelProduct $product,
CompanyNameModuleNameModelProductGalleryVideoProcessor $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' => MagentoProductVideoModelProductAttributeMediaExternalVideoEntryConverter::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 CompanyNameModuleNameModelProductGalleryVideo;
use MagentoFrameworkExceptionLocalizedException;
class Processor extends MagentoCatalogModelProductGalleryProcessor
{
/**
* @var MagentoCatalogModelProductGalleryCreateHandler
*/
protected $createHandler;
/**
* Processor constructor.
* @param MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository
* @param MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb
* @param MagentoCatalogModelProductMediaConfig $mediaConfig
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoCatalogModelResourceModelProductGallery $resourceModel
* @param MagentoCatalogModelProductGalleryCreateHandler $createHandler
*/
public function __construct(
MagentoCatalogApiProductAttributeRepositoryInterface $attributeRepository,
MagentoMediaStorageHelperFileStorageDatabase $fileStorageDb,
MagentoCatalogModelProductMediaConfig $mediaConfig,
MagentoFrameworkFilesystem $filesystem,
MagentoCatalogModelResourceModelProductGallery $resourceModel,
MagentoCatalogModelProductGalleryCreateHandler $createHandler
)
{
parent::__construct($attributeRepository, $fileStorageDb, $mediaConfig, $filesystem, $resourceModel);
$this->createHandler = $createHandler;
}
/**
* @param MagentoCatalogModelProduct $product
* @param array $videoData
* @param array $mediaAttribute
* @param bool $move
* @param bool $exclude
* @return string
* @throws LocalizedException
*/
public function addVideo(
MagentoCatalogModelProduct $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 = MagentoMediaStorageModelFileUploader::getCorrectFileName($pathinfo['basename']);
$dispretionPath = MagentoMediaStorageModelFileUploader::getDispretionPath($fileName);
$fileName = $dispretionPath . '/' . $fileName;
$fileName = $this->getNotDuplicatedFilename($fileName, $dispretionPath);
$destinationFile = $this->mediaConfig->getTmpMediaPath($fileName);
try {
/** @var $storageHelper MagentoMediaStorageHelperFileStorageDatabase */
$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 !!
answered Jul 10 '18 at 20:05
Rohan HapaniRohan Hapani
5,97021662
5,97021662
It returns "The image does not exist." error.
– user69123
Jul 10 '18 at 20:10
Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder.
– Rohan Hapani
Jul 10 '18 at 20:11
Happy coding !! :)
– Rohan Hapani
Jul 10 '18 at 20:15
add a comment |
It returns "The image does not exist." error.
– user69123
Jul 10 '18 at 20:10
Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder.
– Rohan Hapani
Jul 10 '18 at 20:11
Happy coding !! :)
– Rohan Hapani
Jul 10 '18 at 20:15
It returns "The image does not exist." error.
– user69123
Jul 10 '18 at 20:10
It returns "The image does not exist." error.
– user69123
Jul 10 '18 at 20:10
Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder.
– Rohan Hapani
Jul 10 '18 at 20:11
Please check your thumbnail image available in pub/media folder. If not available then upload in pub/media folder.
– Rohan Hapani
Jul 10 '18 at 20:11
Happy coding !! :)
– Rohan Hapani
Jul 10 '18 at 20:15
Happy coding !! :)
– Rohan Hapani
Jul 10 '18 at 20:15
add a comment |
If Display video in product page using mp4 video and another types of video
We have to need create attribute for add video name
Then get this video name to where want to display video
Import videos in video folder in 'pub/media/catalog/product/videos/'
<?php
$_helper = $this->helper('MagentoCatalogHelperOutput');
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$_product = $objectManager->get('MagentoFrameworkRegistry')->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; ?>
add a comment |
If Display video in product page using mp4 video and another types of video
We have to need create attribute for add video name
Then get this video name to where want to display video
Import videos in video folder in 'pub/media/catalog/product/videos/'
<?php
$_helper = $this->helper('MagentoCatalogHelperOutput');
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$_product = $objectManager->get('MagentoFrameworkRegistry')->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; ?>
add a comment |
If Display video in product page using mp4 video and another types of video
We have to need create attribute for add video name
Then get this video name to where want to display video
Import videos in video folder in 'pub/media/catalog/product/videos/'
<?php
$_helper = $this->helper('MagentoCatalogHelperOutput');
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$_product = $objectManager->get('MagentoFrameworkRegistry')->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; ?>
If Display video in product page using mp4 video and another types of video
We have to need create attribute for add video name
Then get this video name to where want to display video
Import videos in video folder in 'pub/media/catalog/product/videos/'
<?php
$_helper = $this->helper('MagentoCatalogHelperOutput');
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$_product = $objectManager->get('MagentoFrameworkRegistry')->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; ?>
answered 26 mins ago
AB SaiyadAB Saiyad
594
594
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f233057%2fmagento-2-2-5-add-video-to-product-programmatically%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e) {
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom)) {
StackExchange.using('gps', function() { StackExchange.gps.track('embedded_signup_form.view', { location: 'question_page' }); });
$window.unbind('scroll', onScroll);
}
};
$window.on('scroll', onScroll);
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown