Magento 2.3. How to create image upload field in an admin formAdmin form field buttonMagento 2 : Added field for image upload in admin formMagento 2 Add new field to Magento_User admin formI have created one field using product form field for my price i want save my field value at product creation time from backend magento2Magento 2.3 Can't view module's front end page output?Magento 2 plugin change price of products that have a custom attribute withHow to create a dynamic fields in admin form?Magento 2.3 Add image field in serilaizedMagento 2.3 Image upload field on CMS PageShow Block class image upload to Ui form image upload
FD Battery Stations... How Do You Log?
Did the CIA blow up a Siberian pipeline in 1982?
I found a password with hashcat, but it doesn't work
Is the specular reflection on a polished gold sphere white or gold in colour?
Dates on degrees don’t make sense – will people care?
Umlaut character order when sorting
What was the flower of Empress Taytu?
What are the pros and cons for the two possible "gear directions" when parking the car on a hill?
What is the oldest commercial MS-DOS program that can run on modern versions of Windows without third-party software?
What is the "ls" directory in my home directory?
Exact functors and derived functors
Improve appearance of the table in Latex
How to work with PETG? Settings, caveats, etc
Find the common ancestor between two nodes of a tree
How can I ping multiple IP addresses at the same time?
"What is the maximum that Player 1 can win?"
Non-misogynistic way to say “asshole”?
How did Gollum enter Moria?
Why is it easier to balance a non-moving bike standing up than sitting down?
What triggered jesuits' ban on infinitesimals in 1632?
Explain why a line can never intersect a plane in exactly two points.
What mathematical theory is required for high frequency trading?
How long did the SR-71 take to get to cruising altitude?
Are there examples of rowers who also fought?
Magento 2.3. How to create image upload field in an admin form
Admin form field buttonMagento 2 : Added field for image upload in admin formMagento 2 Add new field to Magento_User admin formI have created one field using product form field for my price i want save my field value at product creation time from backend magento2Magento 2.3 Can't view module's front end page output?Magento 2 plugin change price of products that have a custom attribute withHow to create a dynamic fields in admin form?Magento 2.3 Add image field in serilaizedMagento 2.3 Image upload field on CMS PageShow Block class image upload to Ui form image upload
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I want to discribe How I have created image upload field in an admin form.
My module's name is ParacrabBanners
- Firstly You should add field in Paracrab/Banners/view/adminhtml/ui_component/name_name_form.xml
<field name="image" sortOrder="30" formElement="imageUploader">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">banner</item>
</item>
</argument>
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">Banner Image</label>
<visible>true</visible>
<required>false</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="banner/banner/upload"/>
</uploaderConfig>
<openDialogTitle>Media Gallery</openDialogTitle>
<initialMediaGalleryOpenSubpath>paracrab/image</initialMediaGalleryOpenSubpath>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
name="image"
it is name field in database.
- Will create admin Controller and Action
<?php
namespace ParacrabBannersControllerAdminhtmlBanner;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoFrameworkControllerResultFactory;
class Upload extends MagentoBackendAppAction implements HttpPostActionInterface
/**
* @var ParacrabBannersModelImageUploader
*/
protected $imageUploader;
public function __construct(
MagentoBackendAppActionContext $context,
ParacrabBannersModelImageUploader $imageUploader
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
/**
* @return MagentoFrameworkAppResponseInterface
Did you notice ParacrabBannersModelImageUploader
in __construct
?
You need create this class.
- Create
ParacrabBannersModelImageUploader
class
<?php
namespace ParacrabBannersModel;
class ImageUploader
/**
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* @var
*/
protected $baseTmpPath;
/**
* @var
*/
protected $basePath;
/**
* @var
*/
protected $allowedExtensions;
/**
* @var array
*/
private $allowedMimeTypes;
/**
* ImageUploader constructor.
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param $baseTmpPath
* @param $basePath
* @param $allowedExtensions
* @param array $allowedMimeTypes
* @throws MagentoFrameworkExceptionFileSystemException
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions,
$allowedMimeTypes = []
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->allowedMimeTypes = $allowedMimeTypes;
/**
* @param $baseTmpPath
*/
public function setBaseTmpPath($baseTmpPath)
$this->baseTmpPath = $baseTmpPath;
/**
* @param $basePath
*/
public function setBasePath($basePath)
$this->basePath = $basePath;
/**
* @param $allowedExtensions
*/
public function setAllowedExtensions($allowedExtensions)
$this->allowedExtensions = $allowedExtensions;
/**
* @return mixed
*/
public function getBaseTmpPath()
return $this->baseTmpPath;
/**
* @return mixed
*/
public function getBasePath()
return $this->basePath;
/**
* @return mixed
*/
public function getAllowedExtensions()
return $this->allowedExtensions;
/**
* @param $path
* @param $imageName
* @return string
*/
public function getFilePath($path, $imageName)
return rtrim($path, '/') . '/' . ltrim($imageName, '/');
/**
* @param $imageName
* @return mixed
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function moveFileFromTmp($imageName)
$baseTmpPath = $this->getBaseTmpPath();
$basePath = $this->getBasePath();
$baseImagePath = $this->getFilePath($basePath, $imageName);
$baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);
try
$this->coreFileStorageDatabase->copyFile(
$baseTmpImagePath,
$baseImagePath
);
$this->mediaDirectory->renameFile(
$baseTmpImagePath,
$baseImagePath
);
catch (Exception $e)
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $imageName;
/**
* @param $fileId
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function saveFileToTmpDir($fileId)
$baseTmpPath = $this->getBaseTmpPath();
/** @var MagentoMediaStorageModelFileUploader $uploader */
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions($this->getAllowedExtensions());
$uploader->setAllowRenameFiles(true);
if (!$uploader->checkMimeType($this->allowedMimeTypes))
throw new MagentoFrameworkExceptionLocalizedException(__('File validation failed.'));
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
unset($result['path']);
if (!$result)
throw new MagentoFrameworkExceptionLocalizedException(
__('File can not be saved to the destination folder.')
);
/**
* Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS
*/
$result['tmp_name'] = str_replace('\', '/', $result['tmp_name']);
$result['url'] = $this->storeManager
->getStore()
->getBaseUrl(
MagentoFrameworkUrlInterface::URL_TYPE_MEDIA
) . $this->getFilePath($baseTmpPath, $result['file']);
$result['name'] = $result['file'];
if (isset($result['file']))
try
$relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');
$this->coreFileStorageDatabase->saveFile($relativePath);
catch (Exception $e)
$this->logger->critical($e);
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
This class was copied from
vendor/magento/module-catalog/Model/ImageUploader.php
- You need create
virtualType
for this class inetc/di.xml
with parameters
<virtualType name="ParacrabBannersImageUploader" type="ParacrabBannersModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">paracrab/tmp/image</argument>
<argument name="basePath" xsi:type="string">paracrab/image</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
<argument name="allowedMimeTypes" xsi:type="array">
<item name="jpg" xsi:type="string">image/jpg</item>
<item name="jpeg" xsi:type="string">image/jpeg</item>
<item name="gif" xsi:type="string">image/gif</item>
<item name="png" xsi:type="string">image/png</item>
</argument>
</arguments>
</virtualType>
<type name="ParacrabBannersControllerAdminhtmlBannerUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
<type name="ParacrabBannersControllerAdminhtmlBannersSave">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
- Also You should create class
Paracrab/Banners/Model/Banner/FileInfo.php
<?php
namespace ParacrabBannersModelBanner;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFileMime;
use MagentoFrameworkFilesystem;
use MagentoFrameworkFilesystemDirectoryWriteInterface;
use MagentoFrameworkFilesystemDirectoryReadInterface;
/**
* Class FileInfo
*
* Provides information about requested file
*/
class FileInfo
/**
* Path in /pub/media directory
*/
const ENTITY_MEDIA_PATH = 'paracrab/image';
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Mime
*/
private $mime;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var ReadInterface
*/
private $baseDirectory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* @param Filesystem $filesystem
* @param Mime $mime
*/
public function __construct(
Filesystem $filesystem,
Mime $mime,
MagentoStoreModelStoreManagerInterface $storeManager
)
$this->filesystem = $filesystem;
$this->mime = $mime;
$this->_storeManager = $storeManager;
/**
* Get WriteInterface instance
*
* @return WriteInterface
*/
public function getMediaDirectory()
if ($this->mediaDirectory === null)
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
return $this->mediaDirectory;
/**
* Get Base Directory read instance
*
* @return ReadInterface
*/
private function getBaseDirectory()
if (!isset($this->baseDirectory))
$this->baseDirectory = $this->filesystem->getDirectoryRead(DirectoryList::ROOT);
return $this->baseDirectory;
/**
* Retrieve MIME type of requested file
*
* @param string $fileName
* @return string
*/
public function getMimeType($fileName)
$filePath = $this->getFilePath($fileName);
$absoluteFilePath = $this->getMediaDirectory()->getAbsolutePath($filePath);
$result = $this->mime->getMimeType($absoluteFilePath);
return $result;
/**
* @param $fileName
* @return string
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function getAbsolutePatch($fileName)
$absoluteFilePath = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
$absoluteFilePath .= $this->getFilePath($fileName);
return $absoluteFilePath;
/**
* Get file statistics data
*
* @param string $fileName
* @return array
*/
public function getStat($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->stat($filePath);
return $result;
/**
* Check if the file exists
*
* @param string $fileName
* @return bool
*/
public function isExist($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->isExist($filePath);
return $result;
/**
* Construct and return file subpath based on filename relative to media directory
*
* @param string $fileName
* @return string
*/
private function getFilePath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = $this->isBeginsWithMediaDirectoryPath($fileName);
// if the file is not using a relative path, it resides in the paracrab/image media directory
$fileIsInModuleMediaDir = !$isFileNameBeginsWithMediaDirectoryPath;
if ($fileIsInModuleMediaDir)
$filePath = self::ENTITY_MEDIA_PATH . '/' . $filePath;
else
$filePath = substr($filePath, strlen($mediaDirectoryRelativeSubpath));
return $filePath;
/**
* Checks for whether $fileName string begins with media directory path
*
* @param string $fileName
* @return bool
*/
public function isBeginsWithMediaDirectoryPath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = strpos($filePath, $mediaDirectoryRelativeSubpath) === 0;
return $isFileNameBeginsWithMediaDirectoryPath;
/**
* Get media directory subpath relative to base directory path
*
* @return string
*/
private function getMediaDirectoryPathRelativeToBaseDirectoryPath()
$baseDirectoryPath = $this->getBaseDirectory()->getAbsolutePath();
$mediaDirectoryPath = $this->getMediaDirectory()->getAbsolutePath();
$mediaDirectoryRelativeSubpath = substr($mediaDirectoryPath, strlen($baseDirectoryPath));
return $mediaDirectoryRelativeSubpath;
This class similar this vendor/magento/module-catalog/Model/Category/FileInfo.php
- You have
DataProvider
for displaing form in whole. This is code myDataProvider
class
<?php
namespace ParacrabBannersModelBanner;
use ParacrabBannersModelResourceModelBannerCollectionFactory as BannerCollectionFactory;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoUiDataProviderModifierPoolInterface;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelBannerFileInfo;
class DataProvider extends MagentoUiDataProviderModifierPoolDataProvider
null $pool
*/
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
BannerCollectionFactory $pageCollectionFactory,
DataPersistorInterface $dataPersistor,
MagentoFrameworkAppRequestHttp $request,
BannerRepositoryInterface $bannerRepository,
FileInfo $fileInfo,
array $meta = [],
array $data = [],
PoolInterface $pool = null
)
$this->collection = $pageCollectionFactory->create();
$this->dataPersistor = $dataPersistor;
$this->request = $request;
$this->bannerRepository = $bannerRepository;
$this->fileInfo = $fileInfo;
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data, $pool);
/**
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function getData()
if (isset($this->loadedData))
return $this->loadedData;
$bannerId = $this->request->getParam('banner_id');
if($bannerId)
$item = $this->bannerRepository->getById($bannerId);
$fileName = $item->getData('image');
if($this->fileInfo->isExist($fileName) && $fileName !== '')
$stat = $this->fileInfo->getStat($fileName);
$image = [
0 => [
'name' => basename($fileName),
'url' => $this->fileInfo->getAbsolutePatch($fileName),
'size' => isset($stat) ? $stat['size'] : 0,
'type' => $this->fileInfo->getMimeType($fileName)
]
];
$item->setData('image', $image);
$this->loadedData[$item->getId()] = $item->getData();
$data = $this->dataPersistor->get('paracrab_banner');
if (!empty($data))
$page = $this->collection->getNewEmptyItem();
$page->setData($data);
$this->loadedData[$page->getId()] = $page->getData();
$this->dataPersistor->clear('paracrab_banner');
return $this->loadedData;
7. You have
Action
for saving data from form. This is how my Action look like<?php
namespace ParacrabBannersControllerAdminhtmlBanners;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoBackendAppActionContext;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkExceptionLocalizedException;
use ParacrabBannersModelBanner;
use ParacrabBannersModelBannerFactory;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelImageUploader;
class Save extends MagentoBackendAppAction implements HttpPostActionInterface
MagentoFrameworkControllerResultRedirect
- Create directories in
pub/media
likeparacrab/images
andparacrab/tmp/images
magento2.3 adminform
add a comment |
I want to discribe How I have created image upload field in an admin form.
My module's name is ParacrabBanners
- Firstly You should add field in Paracrab/Banners/view/adminhtml/ui_component/name_name_form.xml
<field name="image" sortOrder="30" formElement="imageUploader">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">banner</item>
</item>
</argument>
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">Banner Image</label>
<visible>true</visible>
<required>false</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="banner/banner/upload"/>
</uploaderConfig>
<openDialogTitle>Media Gallery</openDialogTitle>
<initialMediaGalleryOpenSubpath>paracrab/image</initialMediaGalleryOpenSubpath>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
name="image"
it is name field in database.
- Will create admin Controller and Action
<?php
namespace ParacrabBannersControllerAdminhtmlBanner;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoFrameworkControllerResultFactory;
class Upload extends MagentoBackendAppAction implements HttpPostActionInterface
/**
* @var ParacrabBannersModelImageUploader
*/
protected $imageUploader;
public function __construct(
MagentoBackendAppActionContext $context,
ParacrabBannersModelImageUploader $imageUploader
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
/**
* @return MagentoFrameworkAppResponseInterface
Did you notice ParacrabBannersModelImageUploader
in __construct
?
You need create this class.
- Create
ParacrabBannersModelImageUploader
class
<?php
namespace ParacrabBannersModel;
class ImageUploader
/**
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* @var
*/
protected $baseTmpPath;
/**
* @var
*/
protected $basePath;
/**
* @var
*/
protected $allowedExtensions;
/**
* @var array
*/
private $allowedMimeTypes;
/**
* ImageUploader constructor.
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param $baseTmpPath
* @param $basePath
* @param $allowedExtensions
* @param array $allowedMimeTypes
* @throws MagentoFrameworkExceptionFileSystemException
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions,
$allowedMimeTypes = []
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->allowedMimeTypes = $allowedMimeTypes;
/**
* @param $baseTmpPath
*/
public function setBaseTmpPath($baseTmpPath)
$this->baseTmpPath = $baseTmpPath;
/**
* @param $basePath
*/
public function setBasePath($basePath)
$this->basePath = $basePath;
/**
* @param $allowedExtensions
*/
public function setAllowedExtensions($allowedExtensions)
$this->allowedExtensions = $allowedExtensions;
/**
* @return mixed
*/
public function getBaseTmpPath()
return $this->baseTmpPath;
/**
* @return mixed
*/
public function getBasePath()
return $this->basePath;
/**
* @return mixed
*/
public function getAllowedExtensions()
return $this->allowedExtensions;
/**
* @param $path
* @param $imageName
* @return string
*/
public function getFilePath($path, $imageName)
return rtrim($path, '/') . '/' . ltrim($imageName, '/');
/**
* @param $imageName
* @return mixed
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function moveFileFromTmp($imageName)
$baseTmpPath = $this->getBaseTmpPath();
$basePath = $this->getBasePath();
$baseImagePath = $this->getFilePath($basePath, $imageName);
$baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);
try
$this->coreFileStorageDatabase->copyFile(
$baseTmpImagePath,
$baseImagePath
);
$this->mediaDirectory->renameFile(
$baseTmpImagePath,
$baseImagePath
);
catch (Exception $e)
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $imageName;
/**
* @param $fileId
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function saveFileToTmpDir($fileId)
$baseTmpPath = $this->getBaseTmpPath();
/** @var MagentoMediaStorageModelFileUploader $uploader */
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions($this->getAllowedExtensions());
$uploader->setAllowRenameFiles(true);
if (!$uploader->checkMimeType($this->allowedMimeTypes))
throw new MagentoFrameworkExceptionLocalizedException(__('File validation failed.'));
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
unset($result['path']);
if (!$result)
throw new MagentoFrameworkExceptionLocalizedException(
__('File can not be saved to the destination folder.')
);
/**
* Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS
*/
$result['tmp_name'] = str_replace('\', '/', $result['tmp_name']);
$result['url'] = $this->storeManager
->getStore()
->getBaseUrl(
MagentoFrameworkUrlInterface::URL_TYPE_MEDIA
) . $this->getFilePath($baseTmpPath, $result['file']);
$result['name'] = $result['file'];
if (isset($result['file']))
try
$relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');
$this->coreFileStorageDatabase->saveFile($relativePath);
catch (Exception $e)
$this->logger->critical($e);
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
This class was copied from
vendor/magento/module-catalog/Model/ImageUploader.php
- You need create
virtualType
for this class inetc/di.xml
with parameters
<virtualType name="ParacrabBannersImageUploader" type="ParacrabBannersModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">paracrab/tmp/image</argument>
<argument name="basePath" xsi:type="string">paracrab/image</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
<argument name="allowedMimeTypes" xsi:type="array">
<item name="jpg" xsi:type="string">image/jpg</item>
<item name="jpeg" xsi:type="string">image/jpeg</item>
<item name="gif" xsi:type="string">image/gif</item>
<item name="png" xsi:type="string">image/png</item>
</argument>
</arguments>
</virtualType>
<type name="ParacrabBannersControllerAdminhtmlBannerUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
<type name="ParacrabBannersControllerAdminhtmlBannersSave">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
- Also You should create class
Paracrab/Banners/Model/Banner/FileInfo.php
<?php
namespace ParacrabBannersModelBanner;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFileMime;
use MagentoFrameworkFilesystem;
use MagentoFrameworkFilesystemDirectoryWriteInterface;
use MagentoFrameworkFilesystemDirectoryReadInterface;
/**
* Class FileInfo
*
* Provides information about requested file
*/
class FileInfo
/**
* Path in /pub/media directory
*/
const ENTITY_MEDIA_PATH = 'paracrab/image';
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Mime
*/
private $mime;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var ReadInterface
*/
private $baseDirectory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* @param Filesystem $filesystem
* @param Mime $mime
*/
public function __construct(
Filesystem $filesystem,
Mime $mime,
MagentoStoreModelStoreManagerInterface $storeManager
)
$this->filesystem = $filesystem;
$this->mime = $mime;
$this->_storeManager = $storeManager;
/**
* Get WriteInterface instance
*
* @return WriteInterface
*/
public function getMediaDirectory()
if ($this->mediaDirectory === null)
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
return $this->mediaDirectory;
/**
* Get Base Directory read instance
*
* @return ReadInterface
*/
private function getBaseDirectory()
if (!isset($this->baseDirectory))
$this->baseDirectory = $this->filesystem->getDirectoryRead(DirectoryList::ROOT);
return $this->baseDirectory;
/**
* Retrieve MIME type of requested file
*
* @param string $fileName
* @return string
*/
public function getMimeType($fileName)
$filePath = $this->getFilePath($fileName);
$absoluteFilePath = $this->getMediaDirectory()->getAbsolutePath($filePath);
$result = $this->mime->getMimeType($absoluteFilePath);
return $result;
/**
* @param $fileName
* @return string
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function getAbsolutePatch($fileName)
$absoluteFilePath = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
$absoluteFilePath .= $this->getFilePath($fileName);
return $absoluteFilePath;
/**
* Get file statistics data
*
* @param string $fileName
* @return array
*/
public function getStat($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->stat($filePath);
return $result;
/**
* Check if the file exists
*
* @param string $fileName
* @return bool
*/
public function isExist($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->isExist($filePath);
return $result;
/**
* Construct and return file subpath based on filename relative to media directory
*
* @param string $fileName
* @return string
*/
private function getFilePath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = $this->isBeginsWithMediaDirectoryPath($fileName);
// if the file is not using a relative path, it resides in the paracrab/image media directory
$fileIsInModuleMediaDir = !$isFileNameBeginsWithMediaDirectoryPath;
if ($fileIsInModuleMediaDir)
$filePath = self::ENTITY_MEDIA_PATH . '/' . $filePath;
else
$filePath = substr($filePath, strlen($mediaDirectoryRelativeSubpath));
return $filePath;
/**
* Checks for whether $fileName string begins with media directory path
*
* @param string $fileName
* @return bool
*/
public function isBeginsWithMediaDirectoryPath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = strpos($filePath, $mediaDirectoryRelativeSubpath) === 0;
return $isFileNameBeginsWithMediaDirectoryPath;
/**
* Get media directory subpath relative to base directory path
*
* @return string
*/
private function getMediaDirectoryPathRelativeToBaseDirectoryPath()
$baseDirectoryPath = $this->getBaseDirectory()->getAbsolutePath();
$mediaDirectoryPath = $this->getMediaDirectory()->getAbsolutePath();
$mediaDirectoryRelativeSubpath = substr($mediaDirectoryPath, strlen($baseDirectoryPath));
return $mediaDirectoryRelativeSubpath;
This class similar this vendor/magento/module-catalog/Model/Category/FileInfo.php
- You have
DataProvider
for displaing form in whole. This is code myDataProvider
class
<?php
namespace ParacrabBannersModelBanner;
use ParacrabBannersModelResourceModelBannerCollectionFactory as BannerCollectionFactory;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoUiDataProviderModifierPoolInterface;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelBannerFileInfo;
class DataProvider extends MagentoUiDataProviderModifierPoolDataProvider
null $pool
*/
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
BannerCollectionFactory $pageCollectionFactory,
DataPersistorInterface $dataPersistor,
MagentoFrameworkAppRequestHttp $request,
BannerRepositoryInterface $bannerRepository,
FileInfo $fileInfo,
array $meta = [],
array $data = [],
PoolInterface $pool = null
)
$this->collection = $pageCollectionFactory->create();
$this->dataPersistor = $dataPersistor;
$this->request = $request;
$this->bannerRepository = $bannerRepository;
$this->fileInfo = $fileInfo;
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data, $pool);
/**
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function getData()
if (isset($this->loadedData))
return $this->loadedData;
$bannerId = $this->request->getParam('banner_id');
if($bannerId)
$item = $this->bannerRepository->getById($bannerId);
$fileName = $item->getData('image');
if($this->fileInfo->isExist($fileName) && $fileName !== '')
$stat = $this->fileInfo->getStat($fileName);
$image = [
0 => [
'name' => basename($fileName),
'url' => $this->fileInfo->getAbsolutePatch($fileName),
'size' => isset($stat) ? $stat['size'] : 0,
'type' => $this->fileInfo->getMimeType($fileName)
]
];
$item->setData('image', $image);
$this->loadedData[$item->getId()] = $item->getData();
$data = $this->dataPersistor->get('paracrab_banner');
if (!empty($data))
$page = $this->collection->getNewEmptyItem();
$page->setData($data);
$this->loadedData[$page->getId()] = $page->getData();
$this->dataPersistor->clear('paracrab_banner');
return $this->loadedData;
7. You have
Action
for saving data from form. This is how my Action look like<?php
namespace ParacrabBannersControllerAdminhtmlBanners;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoBackendAppActionContext;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkExceptionLocalizedException;
use ParacrabBannersModelBanner;
use ParacrabBannersModelBannerFactory;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelImageUploader;
class Save extends MagentoBackendAppAction implements HttpPostActionInterface
MagentoFrameworkControllerResultRedirect
- Create directories in
pub/media
likeparacrab/images
andparacrab/tmp/images
magento2.3 adminform
add a comment |
I want to discribe How I have created image upload field in an admin form.
My module's name is ParacrabBanners
- Firstly You should add field in Paracrab/Banners/view/adminhtml/ui_component/name_name_form.xml
<field name="image" sortOrder="30" formElement="imageUploader">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">banner</item>
</item>
</argument>
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">Banner Image</label>
<visible>true</visible>
<required>false</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="banner/banner/upload"/>
</uploaderConfig>
<openDialogTitle>Media Gallery</openDialogTitle>
<initialMediaGalleryOpenSubpath>paracrab/image</initialMediaGalleryOpenSubpath>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
name="image"
it is name field in database.
- Will create admin Controller and Action
<?php
namespace ParacrabBannersControllerAdminhtmlBanner;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoFrameworkControllerResultFactory;
class Upload extends MagentoBackendAppAction implements HttpPostActionInterface
/**
* @var ParacrabBannersModelImageUploader
*/
protected $imageUploader;
public function __construct(
MagentoBackendAppActionContext $context,
ParacrabBannersModelImageUploader $imageUploader
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
/**
* @return MagentoFrameworkAppResponseInterface
Did you notice ParacrabBannersModelImageUploader
in __construct
?
You need create this class.
- Create
ParacrabBannersModelImageUploader
class
<?php
namespace ParacrabBannersModel;
class ImageUploader
/**
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* @var
*/
protected $baseTmpPath;
/**
* @var
*/
protected $basePath;
/**
* @var
*/
protected $allowedExtensions;
/**
* @var array
*/
private $allowedMimeTypes;
/**
* ImageUploader constructor.
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param $baseTmpPath
* @param $basePath
* @param $allowedExtensions
* @param array $allowedMimeTypes
* @throws MagentoFrameworkExceptionFileSystemException
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions,
$allowedMimeTypes = []
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->allowedMimeTypes = $allowedMimeTypes;
/**
* @param $baseTmpPath
*/
public function setBaseTmpPath($baseTmpPath)
$this->baseTmpPath = $baseTmpPath;
/**
* @param $basePath
*/
public function setBasePath($basePath)
$this->basePath = $basePath;
/**
* @param $allowedExtensions
*/
public function setAllowedExtensions($allowedExtensions)
$this->allowedExtensions = $allowedExtensions;
/**
* @return mixed
*/
public function getBaseTmpPath()
return $this->baseTmpPath;
/**
* @return mixed
*/
public function getBasePath()
return $this->basePath;
/**
* @return mixed
*/
public function getAllowedExtensions()
return $this->allowedExtensions;
/**
* @param $path
* @param $imageName
* @return string
*/
public function getFilePath($path, $imageName)
return rtrim($path, '/') . '/' . ltrim($imageName, '/');
/**
* @param $imageName
* @return mixed
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function moveFileFromTmp($imageName)
$baseTmpPath = $this->getBaseTmpPath();
$basePath = $this->getBasePath();
$baseImagePath = $this->getFilePath($basePath, $imageName);
$baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);
try
$this->coreFileStorageDatabase->copyFile(
$baseTmpImagePath,
$baseImagePath
);
$this->mediaDirectory->renameFile(
$baseTmpImagePath,
$baseImagePath
);
catch (Exception $e)
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $imageName;
/**
* @param $fileId
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function saveFileToTmpDir($fileId)
$baseTmpPath = $this->getBaseTmpPath();
/** @var MagentoMediaStorageModelFileUploader $uploader */
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions($this->getAllowedExtensions());
$uploader->setAllowRenameFiles(true);
if (!$uploader->checkMimeType($this->allowedMimeTypes))
throw new MagentoFrameworkExceptionLocalizedException(__('File validation failed.'));
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
unset($result['path']);
if (!$result)
throw new MagentoFrameworkExceptionLocalizedException(
__('File can not be saved to the destination folder.')
);
/**
* Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS
*/
$result['tmp_name'] = str_replace('\', '/', $result['tmp_name']);
$result['url'] = $this->storeManager
->getStore()
->getBaseUrl(
MagentoFrameworkUrlInterface::URL_TYPE_MEDIA
) . $this->getFilePath($baseTmpPath, $result['file']);
$result['name'] = $result['file'];
if (isset($result['file']))
try
$relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');
$this->coreFileStorageDatabase->saveFile($relativePath);
catch (Exception $e)
$this->logger->critical($e);
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
This class was copied from
vendor/magento/module-catalog/Model/ImageUploader.php
- You need create
virtualType
for this class inetc/di.xml
with parameters
<virtualType name="ParacrabBannersImageUploader" type="ParacrabBannersModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">paracrab/tmp/image</argument>
<argument name="basePath" xsi:type="string">paracrab/image</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
<argument name="allowedMimeTypes" xsi:type="array">
<item name="jpg" xsi:type="string">image/jpg</item>
<item name="jpeg" xsi:type="string">image/jpeg</item>
<item name="gif" xsi:type="string">image/gif</item>
<item name="png" xsi:type="string">image/png</item>
</argument>
</arguments>
</virtualType>
<type name="ParacrabBannersControllerAdminhtmlBannerUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
<type name="ParacrabBannersControllerAdminhtmlBannersSave">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
- Also You should create class
Paracrab/Banners/Model/Banner/FileInfo.php
<?php
namespace ParacrabBannersModelBanner;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFileMime;
use MagentoFrameworkFilesystem;
use MagentoFrameworkFilesystemDirectoryWriteInterface;
use MagentoFrameworkFilesystemDirectoryReadInterface;
/**
* Class FileInfo
*
* Provides information about requested file
*/
class FileInfo
/**
* Path in /pub/media directory
*/
const ENTITY_MEDIA_PATH = 'paracrab/image';
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Mime
*/
private $mime;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var ReadInterface
*/
private $baseDirectory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* @param Filesystem $filesystem
* @param Mime $mime
*/
public function __construct(
Filesystem $filesystem,
Mime $mime,
MagentoStoreModelStoreManagerInterface $storeManager
)
$this->filesystem = $filesystem;
$this->mime = $mime;
$this->_storeManager = $storeManager;
/**
* Get WriteInterface instance
*
* @return WriteInterface
*/
public function getMediaDirectory()
if ($this->mediaDirectory === null)
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
return $this->mediaDirectory;
/**
* Get Base Directory read instance
*
* @return ReadInterface
*/
private function getBaseDirectory()
if (!isset($this->baseDirectory))
$this->baseDirectory = $this->filesystem->getDirectoryRead(DirectoryList::ROOT);
return $this->baseDirectory;
/**
* Retrieve MIME type of requested file
*
* @param string $fileName
* @return string
*/
public function getMimeType($fileName)
$filePath = $this->getFilePath($fileName);
$absoluteFilePath = $this->getMediaDirectory()->getAbsolutePath($filePath);
$result = $this->mime->getMimeType($absoluteFilePath);
return $result;
/**
* @param $fileName
* @return string
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function getAbsolutePatch($fileName)
$absoluteFilePath = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
$absoluteFilePath .= $this->getFilePath($fileName);
return $absoluteFilePath;
/**
* Get file statistics data
*
* @param string $fileName
* @return array
*/
public function getStat($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->stat($filePath);
return $result;
/**
* Check if the file exists
*
* @param string $fileName
* @return bool
*/
public function isExist($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->isExist($filePath);
return $result;
/**
* Construct and return file subpath based on filename relative to media directory
*
* @param string $fileName
* @return string
*/
private function getFilePath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = $this->isBeginsWithMediaDirectoryPath($fileName);
// if the file is not using a relative path, it resides in the paracrab/image media directory
$fileIsInModuleMediaDir = !$isFileNameBeginsWithMediaDirectoryPath;
if ($fileIsInModuleMediaDir)
$filePath = self::ENTITY_MEDIA_PATH . '/' . $filePath;
else
$filePath = substr($filePath, strlen($mediaDirectoryRelativeSubpath));
return $filePath;
/**
* Checks for whether $fileName string begins with media directory path
*
* @param string $fileName
* @return bool
*/
public function isBeginsWithMediaDirectoryPath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = strpos($filePath, $mediaDirectoryRelativeSubpath) === 0;
return $isFileNameBeginsWithMediaDirectoryPath;
/**
* Get media directory subpath relative to base directory path
*
* @return string
*/
private function getMediaDirectoryPathRelativeToBaseDirectoryPath()
$baseDirectoryPath = $this->getBaseDirectory()->getAbsolutePath();
$mediaDirectoryPath = $this->getMediaDirectory()->getAbsolutePath();
$mediaDirectoryRelativeSubpath = substr($mediaDirectoryPath, strlen($baseDirectoryPath));
return $mediaDirectoryRelativeSubpath;
This class similar this vendor/magento/module-catalog/Model/Category/FileInfo.php
- You have
DataProvider
for displaing form in whole. This is code myDataProvider
class
<?php
namespace ParacrabBannersModelBanner;
use ParacrabBannersModelResourceModelBannerCollectionFactory as BannerCollectionFactory;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoUiDataProviderModifierPoolInterface;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelBannerFileInfo;
class DataProvider extends MagentoUiDataProviderModifierPoolDataProvider
null $pool
*/
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
BannerCollectionFactory $pageCollectionFactory,
DataPersistorInterface $dataPersistor,
MagentoFrameworkAppRequestHttp $request,
BannerRepositoryInterface $bannerRepository,
FileInfo $fileInfo,
array $meta = [],
array $data = [],
PoolInterface $pool = null
)
$this->collection = $pageCollectionFactory->create();
$this->dataPersistor = $dataPersistor;
$this->request = $request;
$this->bannerRepository = $bannerRepository;
$this->fileInfo = $fileInfo;
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data, $pool);
/**
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function getData()
if (isset($this->loadedData))
return $this->loadedData;
$bannerId = $this->request->getParam('banner_id');
if($bannerId)
$item = $this->bannerRepository->getById($bannerId);
$fileName = $item->getData('image');
if($this->fileInfo->isExist($fileName) && $fileName !== '')
$stat = $this->fileInfo->getStat($fileName);
$image = [
0 => [
'name' => basename($fileName),
'url' => $this->fileInfo->getAbsolutePatch($fileName),
'size' => isset($stat) ? $stat['size'] : 0,
'type' => $this->fileInfo->getMimeType($fileName)
]
];
$item->setData('image', $image);
$this->loadedData[$item->getId()] = $item->getData();
$data = $this->dataPersistor->get('paracrab_banner');
if (!empty($data))
$page = $this->collection->getNewEmptyItem();
$page->setData($data);
$this->loadedData[$page->getId()] = $page->getData();
$this->dataPersistor->clear('paracrab_banner');
return $this->loadedData;
7. You have
Action
for saving data from form. This is how my Action look like<?php
namespace ParacrabBannersControllerAdminhtmlBanners;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoBackendAppActionContext;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkExceptionLocalizedException;
use ParacrabBannersModelBanner;
use ParacrabBannersModelBannerFactory;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelImageUploader;
class Save extends MagentoBackendAppAction implements HttpPostActionInterface
MagentoFrameworkControllerResultRedirect
- Create directories in
pub/media
likeparacrab/images
andparacrab/tmp/images
magento2.3 adminform
I want to discribe How I have created image upload field in an admin form.
My module's name is ParacrabBanners
- Firstly You should add field in Paracrab/Banners/view/adminhtml/ui_component/name_name_form.xml
<field name="image" sortOrder="30" formElement="imageUploader">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">banner</item>
</item>
</argument>
<settings>
<elementTmpl>ui/form/element/uploader/image</elementTmpl>
<dataType>string</dataType>
<label translate="true">Banner Image</label>
<visible>true</visible>
<required>false</required>
</settings>
<formElements>
<imageUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="banner/banner/upload"/>
</uploaderConfig>
<openDialogTitle>Media Gallery</openDialogTitle>
<initialMediaGalleryOpenSubpath>paracrab/image</initialMediaGalleryOpenSubpath>
<allowedExtensions>jpg jpeg gif png</allowedExtensions>
<maxFileSize>4194304</maxFileSize>
</settings>
</imageUploader>
</formElements>
</field>
name="image"
it is name field in database.
- Will create admin Controller and Action
<?php
namespace ParacrabBannersControllerAdminhtmlBanner;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoFrameworkControllerResultFactory;
class Upload extends MagentoBackendAppAction implements HttpPostActionInterface
/**
* @var ParacrabBannersModelImageUploader
*/
protected $imageUploader;
public function __construct(
MagentoBackendAppActionContext $context,
ParacrabBannersModelImageUploader $imageUploader
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
/**
* @return MagentoFrameworkAppResponseInterface
Did you notice ParacrabBannersModelImageUploader
in __construct
?
You need create this class.
- Create
ParacrabBannersModelImageUploader
class
<?php
namespace ParacrabBannersModel;
class ImageUploader
/**
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* @var
*/
protected $baseTmpPath;
/**
* @var
*/
protected $basePath;
/**
* @var
*/
protected $allowedExtensions;
/**
* @var array
*/
private $allowedMimeTypes;
/**
* ImageUploader constructor.
* @param MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase
* @param MagentoFrameworkFilesystem $filesystem
* @param MagentoMediaStorageModelFileUploaderFactory $uploaderFactory
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param PsrLogLoggerInterface $logger
* @param $baseTmpPath
* @param $basePath
* @param $allowedExtensions
* @param array $allowedMimeTypes
* @throws MagentoFrameworkExceptionFileSystemException
*/
public function __construct(
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
MagentoFrameworkFilesystem $filesystem,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
PsrLogLoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions,
$allowedMimeTypes = []
)
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->allowedMimeTypes = $allowedMimeTypes;
/**
* @param $baseTmpPath
*/
public function setBaseTmpPath($baseTmpPath)
$this->baseTmpPath = $baseTmpPath;
/**
* @param $basePath
*/
public function setBasePath($basePath)
$this->basePath = $basePath;
/**
* @param $allowedExtensions
*/
public function setAllowedExtensions($allowedExtensions)
$this->allowedExtensions = $allowedExtensions;
/**
* @return mixed
*/
public function getBaseTmpPath()
return $this->baseTmpPath;
/**
* @return mixed
*/
public function getBasePath()
return $this->basePath;
/**
* @return mixed
*/
public function getAllowedExtensions()
return $this->allowedExtensions;
/**
* @param $path
* @param $imageName
* @return string
*/
public function getFilePath($path, $imageName)
return rtrim($path, '/') . '/' . ltrim($imageName, '/');
/**
* @param $imageName
* @return mixed
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function moveFileFromTmp($imageName)
$baseTmpPath = $this->getBaseTmpPath();
$basePath = $this->getBasePath();
$baseImagePath = $this->getFilePath($basePath, $imageName);
$baseTmpImagePath = $this->getFilePath($baseTmpPath, $imageName);
try
$this->coreFileStorageDatabase->copyFile(
$baseTmpImagePath,
$baseImagePath
);
$this->mediaDirectory->renameFile(
$baseTmpImagePath,
$baseImagePath
);
catch (Exception $e)
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $imageName;
/**
* @param $fileId
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function saveFileToTmpDir($fileId)
$baseTmpPath = $this->getBaseTmpPath();
/** @var MagentoMediaStorageModelFileUploader $uploader */
$uploader = $this->uploaderFactory->create(['fileId' => $fileId]);
$uploader->setAllowedExtensions($this->getAllowedExtensions());
$uploader->setAllowRenameFiles(true);
if (!$uploader->checkMimeType($this->allowedMimeTypes))
throw new MagentoFrameworkExceptionLocalizedException(__('File validation failed.'));
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
unset($result['path']);
if (!$result)
throw new MagentoFrameworkExceptionLocalizedException(
__('File can not be saved to the destination folder.')
);
/**
* Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS
*/
$result['tmp_name'] = str_replace('\', '/', $result['tmp_name']);
$result['url'] = $this->storeManager
->getStore()
->getBaseUrl(
MagentoFrameworkUrlInterface::URL_TYPE_MEDIA
) . $this->getFilePath($baseTmpPath, $result['file']);
$result['name'] = $result['file'];
if (isset($result['file']))
try
$relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/');
$this->coreFileStorageDatabase->saveFile($relativePath);
catch (Exception $e)
$this->logger->critical($e);
throw new MagentoFrameworkExceptionLocalizedException(
__('Something went wrong while saving the file(s).')
);
return $result;
This class was copied from
vendor/magento/module-catalog/Model/ImageUploader.php
- You need create
virtualType
for this class inetc/di.xml
with parameters
<virtualType name="ParacrabBannersImageUploader" type="ParacrabBannersModelImageUploader">
<arguments>
<argument name="baseTmpPath" xsi:type="string">paracrab/tmp/image</argument>
<argument name="basePath" xsi:type="string">paracrab/image</argument>
<argument name="allowedExtensions" xsi:type="array">
<item name="jpg" xsi:type="string">jpg</item>
<item name="jpeg" xsi:type="string">jpeg</item>
<item name="gif" xsi:type="string">gif</item>
<item name="png" xsi:type="string">png</item>
</argument>
<argument name="allowedMimeTypes" xsi:type="array">
<item name="jpg" xsi:type="string">image/jpg</item>
<item name="jpeg" xsi:type="string">image/jpeg</item>
<item name="gif" xsi:type="string">image/gif</item>
<item name="png" xsi:type="string">image/png</item>
</argument>
</arguments>
</virtualType>
<type name="ParacrabBannersControllerAdminhtmlBannerUpload">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
<type name="ParacrabBannersControllerAdminhtmlBannersSave">
<arguments>
<argument name="imageUploader" xsi:type="object">ParacrabBannersImageUploader</argument>
</arguments>
</type>
- Also You should create class
Paracrab/Banners/Model/Banner/FileInfo.php
<?php
namespace ParacrabBannersModelBanner;
use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoFrameworkFileMime;
use MagentoFrameworkFilesystem;
use MagentoFrameworkFilesystemDirectoryWriteInterface;
use MagentoFrameworkFilesystemDirectoryReadInterface;
/**
* Class FileInfo
*
* Provides information about requested file
*/
class FileInfo
/**
* Path in /pub/media directory
*/
const ENTITY_MEDIA_PATH = 'paracrab/image';
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Mime
*/
private $mime;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var ReadInterface
*/
private $baseDirectory;
/**
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* @param Filesystem $filesystem
* @param Mime $mime
*/
public function __construct(
Filesystem $filesystem,
Mime $mime,
MagentoStoreModelStoreManagerInterface $storeManager
)
$this->filesystem = $filesystem;
$this->mime = $mime;
$this->_storeManager = $storeManager;
/**
* Get WriteInterface instance
*
* @return WriteInterface
*/
public function getMediaDirectory()
if ($this->mediaDirectory === null)
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
return $this->mediaDirectory;
/**
* Get Base Directory read instance
*
* @return ReadInterface
*/
private function getBaseDirectory()
if (!isset($this->baseDirectory))
$this->baseDirectory = $this->filesystem->getDirectoryRead(DirectoryList::ROOT);
return $this->baseDirectory;
/**
* Retrieve MIME type of requested file
*
* @param string $fileName
* @return string
*/
public function getMimeType($fileName)
$filePath = $this->getFilePath($fileName);
$absoluteFilePath = $this->getMediaDirectory()->getAbsolutePath($filePath);
$result = $this->mime->getMimeType($absoluteFilePath);
return $result;
/**
* @param $fileName
* @return string
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
public function getAbsolutePatch($fileName)
$absoluteFilePath = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
$absoluteFilePath .= $this->getFilePath($fileName);
return $absoluteFilePath;
/**
* Get file statistics data
*
* @param string $fileName
* @return array
*/
public function getStat($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->stat($filePath);
return $result;
/**
* Check if the file exists
*
* @param string $fileName
* @return bool
*/
public function isExist($fileName)
$filePath = $this->getFilePath($fileName);
$result = $this->getMediaDirectory()->isExist($filePath);
return $result;
/**
* Construct and return file subpath based on filename relative to media directory
*
* @param string $fileName
* @return string
*/
private function getFilePath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = $this->isBeginsWithMediaDirectoryPath($fileName);
// if the file is not using a relative path, it resides in the paracrab/image media directory
$fileIsInModuleMediaDir = !$isFileNameBeginsWithMediaDirectoryPath;
if ($fileIsInModuleMediaDir)
$filePath = self::ENTITY_MEDIA_PATH . '/' . $filePath;
else
$filePath = substr($filePath, strlen($mediaDirectoryRelativeSubpath));
return $filePath;
/**
* Checks for whether $fileName string begins with media directory path
*
* @param string $fileName
* @return bool
*/
public function isBeginsWithMediaDirectoryPath($fileName)
$filePath = ltrim($fileName, '/');
$mediaDirectoryRelativeSubpath = $this->getMediaDirectoryPathRelativeToBaseDirectoryPath();
$isFileNameBeginsWithMediaDirectoryPath = strpos($filePath, $mediaDirectoryRelativeSubpath) === 0;
return $isFileNameBeginsWithMediaDirectoryPath;
/**
* Get media directory subpath relative to base directory path
*
* @return string
*/
private function getMediaDirectoryPathRelativeToBaseDirectoryPath()
$baseDirectoryPath = $this->getBaseDirectory()->getAbsolutePath();
$mediaDirectoryPath = $this->getMediaDirectory()->getAbsolutePath();
$mediaDirectoryRelativeSubpath = substr($mediaDirectoryPath, strlen($baseDirectoryPath));
return $mediaDirectoryRelativeSubpath;
This class similar this vendor/magento/module-catalog/Model/Category/FileInfo.php
- You have
DataProvider
for displaing form in whole. This is code myDataProvider
class
<?php
namespace ParacrabBannersModelBanner;
use ParacrabBannersModelResourceModelBannerCollectionFactory as BannerCollectionFactory;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoUiDataProviderModifierPoolInterface;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelBannerFileInfo;
class DataProvider extends MagentoUiDataProviderModifierPoolDataProvider
null $pool
*/
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
BannerCollectionFactory $pageCollectionFactory,
DataPersistorInterface $dataPersistor,
MagentoFrameworkAppRequestHttp $request,
BannerRepositoryInterface $bannerRepository,
FileInfo $fileInfo,
array $meta = [],
array $data = [],
PoolInterface $pool = null
)
$this->collection = $pageCollectionFactory->create();
$this->dataPersistor = $dataPersistor;
$this->request = $request;
$this->bannerRepository = $bannerRepository;
$this->fileInfo = $fileInfo;
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data, $pool);
/**
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function getData()
if (isset($this->loadedData))
return $this->loadedData;
$bannerId = $this->request->getParam('banner_id');
if($bannerId)
$item = $this->bannerRepository->getById($bannerId);
$fileName = $item->getData('image');
if($this->fileInfo->isExist($fileName) && $fileName !== '')
$stat = $this->fileInfo->getStat($fileName);
$image = [
0 => [
'name' => basename($fileName),
'url' => $this->fileInfo->getAbsolutePatch($fileName),
'size' => isset($stat) ? $stat['size'] : 0,
'type' => $this->fileInfo->getMimeType($fileName)
]
];
$item->setData('image', $image);
$this->loadedData[$item->getId()] = $item->getData();
$data = $this->dataPersistor->get('paracrab_banner');
if (!empty($data))
$page = $this->collection->getNewEmptyItem();
$page->setData($data);
$this->loadedData[$page->getId()] = $page->getData();
$this->dataPersistor->clear('paracrab_banner');
return $this->loadedData;
7. You have
Action
for saving data from form. This is how my Action look like<?php
namespace ParacrabBannersControllerAdminhtmlBanners;
use MagentoFrameworkAppActionHttpPostActionInterface;
use MagentoBackendAppActionContext;
use MagentoFrameworkAppRequestDataPersistorInterface;
use MagentoFrameworkExceptionLocalizedException;
use ParacrabBannersModelBanner;
use ParacrabBannersModelBannerFactory;
use ParacrabBannersApiBannerRepositoryInterface;
use ParacrabBannersModelImageUploader;
class Save extends MagentoBackendAppAction implements HttpPostActionInterface
MagentoFrameworkControllerResultRedirect
- Create directories in
pub/media
likeparacrab/images
andparacrab/tmp/images
magento2.3 adminform
magento2.3 adminform
asked Jun 11 at 16:24
Oleg UsikOleg Usik
112
112
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Upload the Custom image at Category
1.Create a InstallData.php file at vendorModuleSetup and add the below code into the InstallData.php
Create a InstallData.php file on location vendorModuleSetup
<?php
namespace VendorModuleSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;
/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
/**
* @inheritdoc
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelCategory::ENTITY, 'custom_catimg', [
'type' => 'varchar',
'label' => 'Custom category image',
'input' => 'image',
'backend' => 'MagentoCatalogModelCategoryAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
2.Create a category_form.xml file into vendorModuleviewadminhtmlui_component and write down the below code
In this file, you have to change the field name as per your attribute code and url as per your controller
like path="module/category_catimg/upload"/ there are module is the route.xml in etc/adminhtm/route.xml name
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_catimg">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/category_catimg/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>
now add the below code into the Vendor/Module/etc/di.xml
MagentoCatalogCategoryImageUpload
catalog/tmp/category
catalog/category
jpg
jpeg
gif
png
4.Create Upload.php file into Vendor/Module/Controller/Adminhtml/Category/Image and write down the below code
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.now create DataProvider.php file on location VendorModuleModelCategory and write down the below code
reate Upload.php file on location Vendor/Module/Controller/Adminhtml/Category/Image
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.create DataProvider.php file on location VendorModuleModelCategory
<?php
namespace VendorModuleModelCategory;
class DataProvider extends MagentoCatalogModelCategoryDataProvider
protected function getFieldsMap()
$fields = parent::getFieldsMap();
$fields['content'][] = 'custom_catimg'; // custom image field
return $fields;
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');
);
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%2f277992%2fmagento-2-3-how-to-create-image-upload-field-in-an-admin-form%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Upload the Custom image at Category
1.Create a InstallData.php file at vendorModuleSetup and add the below code into the InstallData.php
Create a InstallData.php file on location vendorModuleSetup
<?php
namespace VendorModuleSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;
/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
/**
* @inheritdoc
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelCategory::ENTITY, 'custom_catimg', [
'type' => 'varchar',
'label' => 'Custom category image',
'input' => 'image',
'backend' => 'MagentoCatalogModelCategoryAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
2.Create a category_form.xml file into vendorModuleviewadminhtmlui_component and write down the below code
In this file, you have to change the field name as per your attribute code and url as per your controller
like path="module/category_catimg/upload"/ there are module is the route.xml in etc/adminhtm/route.xml name
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_catimg">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/category_catimg/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>
now add the below code into the Vendor/Module/etc/di.xml
MagentoCatalogCategoryImageUpload
catalog/tmp/category
catalog/category
jpg
jpeg
gif
png
4.Create Upload.php file into Vendor/Module/Controller/Adminhtml/Category/Image and write down the below code
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.now create DataProvider.php file on location VendorModuleModelCategory and write down the below code
reate Upload.php file on location Vendor/Module/Controller/Adminhtml/Category/Image
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.create DataProvider.php file on location VendorModuleModelCategory
<?php
namespace VendorModuleModelCategory;
class DataProvider extends MagentoCatalogModelCategoryDataProvider
protected function getFieldsMap()
$fields = parent::getFieldsMap();
$fields['content'][] = 'custom_catimg'; // custom image field
return $fields;
add a comment |
Upload the Custom image at Category
1.Create a InstallData.php file at vendorModuleSetup and add the below code into the InstallData.php
Create a InstallData.php file on location vendorModuleSetup
<?php
namespace VendorModuleSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;
/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
/**
* @inheritdoc
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelCategory::ENTITY, 'custom_catimg', [
'type' => 'varchar',
'label' => 'Custom category image',
'input' => 'image',
'backend' => 'MagentoCatalogModelCategoryAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
2.Create a category_form.xml file into vendorModuleviewadminhtmlui_component and write down the below code
In this file, you have to change the field name as per your attribute code and url as per your controller
like path="module/category_catimg/upload"/ there are module is the route.xml in etc/adminhtm/route.xml name
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_catimg">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/category_catimg/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>
now add the below code into the Vendor/Module/etc/di.xml
MagentoCatalogCategoryImageUpload
catalog/tmp/category
catalog/category
jpg
jpeg
gif
png
4.Create Upload.php file into Vendor/Module/Controller/Adminhtml/Category/Image and write down the below code
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.now create DataProvider.php file on location VendorModuleModelCategory and write down the below code
reate Upload.php file on location Vendor/Module/Controller/Adminhtml/Category/Image
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.create DataProvider.php file on location VendorModuleModelCategory
<?php
namespace VendorModuleModelCategory;
class DataProvider extends MagentoCatalogModelCategoryDataProvider
protected function getFieldsMap()
$fields = parent::getFieldsMap();
$fields['content'][] = 'custom_catimg'; // custom image field
return $fields;
add a comment |
Upload the Custom image at Category
1.Create a InstallData.php file at vendorModuleSetup and add the below code into the InstallData.php
Create a InstallData.php file on location vendorModuleSetup
<?php
namespace VendorModuleSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;
/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
/**
* @inheritdoc
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelCategory::ENTITY, 'custom_catimg', [
'type' => 'varchar',
'label' => 'Custom category image',
'input' => 'image',
'backend' => 'MagentoCatalogModelCategoryAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
2.Create a category_form.xml file into vendorModuleviewadminhtmlui_component and write down the below code
In this file, you have to change the field name as per your attribute code and url as per your controller
like path="module/category_catimg/upload"/ there are module is the route.xml in etc/adminhtm/route.xml name
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_catimg">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/category_catimg/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>
now add the below code into the Vendor/Module/etc/di.xml
MagentoCatalogCategoryImageUpload
catalog/tmp/category
catalog/category
jpg
jpeg
gif
png
4.Create Upload.php file into Vendor/Module/Controller/Adminhtml/Category/Image and write down the below code
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.now create DataProvider.php file on location VendorModuleModelCategory and write down the below code
reate Upload.php file on location Vendor/Module/Controller/Adminhtml/Category/Image
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.create DataProvider.php file on location VendorModuleModelCategory
<?php
namespace VendorModuleModelCategory;
class DataProvider extends MagentoCatalogModelCategoryDataProvider
protected function getFieldsMap()
$fields = parent::getFieldsMap();
$fields['content'][] = 'custom_catimg'; // custom image field
return $fields;
Upload the Custom image at Category
1.Create a InstallData.php file at vendorModuleSetup and add the below code into the InstallData.php
Create a InstallData.php file on location vendorModuleSetup
<?php
namespace VendorModuleSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoEavModelEntityAttributeScopedAttributeInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
/**
* EAV setup factory.
*
* @var EavSetupFactory
*/
private $_eavSetupFactory;
protected $categorySetupFactory;
/**
* Init.
*
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(EavSetupFactory $eavSetupFactory, MagentoCatalogSetupCategorySetupFactory $categorySetupFactory)
$this->_eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
/**
* @inheritdoc
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
/** @var EavSetup $eavSetup */
$eavSetup = $this->_eavSetupFactory->create(['setup' => $setup]);
$setup = $this->categorySetupFactory->create(['setup' => $setup]);
$setup->addAttribute(
MagentoCatalogModelCategory::ENTITY, 'custom_catimg', [
'type' => 'varchar',
'label' => 'Custom category image',
'input' => 'image',
'backend' => 'MagentoCatalogModelCategoryAttributeBackendImage',
'required' => false,
'sort_order' => 9,
'global' => MagentoEavModelEntityAttributeScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]
);
2.Create a category_form.xml file into vendorModuleviewadminhtmlui_component and write down the below code
In this file, you have to change the field name as per your attribute code and url as per your controller
like path="module/category_catimg/upload"/ there are module is the route.xml in etc/adminhtm/route.xml name
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="content">
<field name="custom_catimg">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">string</item>
<item name="source" xsi:type="string">category</item>
<item name="label" xsi:type="string" translate="true">Custom Image</item>
<item name="visible" xsi:type="boolean">true</item>
<item name="formElement" xsi:type="string">fileUploader</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
<item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
<item name="required" xsi:type="boolean">false</item>
<item name="sortOrder" xsi:type="number">40</item>
<item name="uploaderConfig" xsi:type="array">
<item name="url" xsi:type="url" path="module/category_catimg/upload"/>
</item>
</item>
</argument>
</field>
</fieldset>
</form>
now add the below code into the Vendor/Module/etc/di.xml
MagentoCatalogCategoryImageUpload
catalog/tmp/category
catalog/category
jpg
jpeg
gif
png
4.Create Upload.php file into Vendor/Module/Controller/Adminhtml/Category/Image and write down the below code
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.now create DataProvider.php file on location VendorModuleModelCategory and write down the below code
reate Upload.php file on location Vendor/Module/Controller/Adminhtml/Category/Image
<?php
namespace VendorModuleControllerAdminhtmlCategoryImage;
use MagentoFrameworkControllerResultFactory;
/**
* Agorae Adminhtml Category Image Upload Controller
*/
class Upload extends MagentoBackendAppAction
/**
* Image uploader
*
* @var MagentoCatalogModelImageUploader
*/
protected $imageUploader;
/**
* Uploader factory
*
* @var MagentoMediaStorageModelFileUploaderFactory
*/
private $uploaderFactory;
/**
* Media directory object (writable).
*
* @var MagentoFrameworkFilesystemDirectoryWriteInterface
*/
protected $mediaDirectory;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $storeManager;
/**
* Core file storage database
*
* @var MagentoMediaStorageHelperFileStorageDatabase
*/
protected $coreFileStorageDatabase;
/**
* @var PsrLogLoggerInterface
*/
protected $logger;
/**
* Upload constructor.
*
* @param MagentoBackendAppActionContext $context
* @param MagentoCatalogModelImageUploader $imageUploader
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoCatalogModelImageUploader $imageUploader,
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
MagentoFrameworkFilesystem $filesystem,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoMediaStorageHelperFileStorageDatabase $coreFileStorageDatabase,
PsrLogLoggerInterface $logger
)
parent::__construct($context);
$this->imageUploader = $imageUploader;
$this->uploaderFactory = $uploaderFactory;
$this->mediaDirectory = $filesystem->getDirectoryWrite(MagentoFrameworkAppFilesystemDirectoryList::MEDIA);
$this->storeManager = $storeManager;
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->logger = $logger;
/**
* Check admin permissions for this controller
*
* @return boolean
*/
protected function _isAllowed()
return $this->_authorization->isAllowed('Vendor_Module::category');
/**
* Upload file controller action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
try
$result = $this->imageUploader->saveFileToTmpDir('custom_catimg');
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
catch (Exception $e)
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
5.create DataProvider.php file on location VendorModuleModelCategory
<?php
namespace VendorModuleModelCategory;
class DataProvider extends MagentoCatalogModelCategoryDataProvider
protected function getFieldsMap()
$fields = parent::getFieldsMap();
$fields['content'][] = 'custom_catimg'; // custom image field
return $fields;
answered Jun 11 at 17:10
Rasik MiyaniRasik Miyani
1329
1329
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');
);
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%2f277992%2fmagento-2-3-how-to-create-image-upload-field-in-an-admin-form%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');
);
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');
);
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');
);
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