I have the following problem, right now my program uploads the images and does it good, however when i go to the edit product page, the following are empty or uncheked:
- Role
- Alt text
Here is the code i use:
<?php
namespace Vendor\Module\Model\Adminhtml\Product\MediaGallery;
use \Magento\Catalog\Model\Product\Gallery\EntryFactory;
use \Magento\Catalog\Model\Product\Gallery\GalleryManagement;
use \Magento\Framework\Api\ImageContentFactory;
class ImageUpload extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var \Magento\Catalog\Model\Product\Gallery\EntryFactory
*/
private $mediaGalleryEntryFactory;
/**
* @var \Magento\Catalog\Model\Product\Gallery\GalleryManagement
*/
private $mediaGalleryManagement;
/**
* @var \Magento\Framework\Api\ImageContentFactory
*/
private $imageContentFactory;
/**
* @param \Magento\Catalog\Model\Product\Gallery\EntryFactory $mediaGalleryEntryFactory
* @param \Magento\Catalog\Model\Product\Gallery\GalleryManagement $mediaGalleryManagement
* @param \Magento\Framework\Api\ImageContentFactory $imageContentFactory
*/
public function __construct(
EntryFactory $mediaGalleryEntryFactory,
GalleryManagement $mediaGalleryManagement,
ImageContentFactory $imageContentFactory
)
{
$this->mediaGalleryEntryFactory = $mediaGalleryEntryFactory;
$this->mediaGalleryManagement = $mediaGalleryManagement;
$this->imageContentFactory = $imageContentFactory;
}
/**
* @param string $filePath
* @param string $sku
*/
public function processMediaGalleryEntry($filePath, $sku, $productName, $additional = false, $position = 0)
{
$entry = $this->mediaGalleryEntryFactory->create();
$entry->setFile($filePath)
->setMediaType('image')
->setDisabled(false)
->setLabel($productName);
if($additional)
{
$entry->setPosition($position);
$entry->setTypes(['thumbnail']);
}
else
{
$entry->setTypes(['thumbnail', 'image', 'small_image']);
$entry->setPosition($position);
}
$imageContent = $this->imageContentFactory->create();
$imageContent->setType(mime_content_type($filePath))
->setName($productName)
->setBase64EncodedData(base64_encode(file_get_contents($filePath)));
$entry->setContent($imageContent);
$this->mediaGalleryManagement->create($sku, $entry);
}
}
What happens in edit page is this:
