How to do image uploader in the custom form field in magento 2 backen
_prepareForm()
$fieldset->addField(
'proimage',
'image',
[
'title' => __('Image'),
'label' => __(' Image'),
'name' => 'proimage',
'note' => 'Allow image type: jpg, jpeg, gif, png',
]
);
Save.php controller
<?php
namespace Cm\Productlabel\Controller\Adminhtml\Label;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends Action
{
/**
* @param Action\Context $context
*/
public function __construct(
Action\Context $context,
)
{
parent::__construct($context);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Cm_Productlabel::save');
}
public function execute()
{
$isPost = $this->getRequest()->getPost();
$resultRedirect = $this->resultRedirectFactory->create();
if ($isPost) {
$model = $this->_objectManager-
>create('Cm\Productlabel\Model\Productlabel');
$postId = $this->getRequest()->getParam('productlabel_id');
if ($postId) {
$model->load($postId);
}
$profileImage = $this->getRequest()->getFiles('proimage');
$fileName = ($profileImage && array_key_exists('name', $profileImage)) ?
$profileImage['name'] : null;
if ($profileImage && $fileName) {
try {
$uploader = $this->_objectManager->create(
'Magento\MediaStorage\Model\File\Uploader',
['fileId' => 'proimage']
);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
/** @var \Magento\Framework\Image\Adapter\AdapterInterface
$imageAdapterFactory */
$imageAdapterFactory = $this->_objectManager-
>get('Magento\Framework\Image\AdapterFactory')
->create();
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
/** @var \Magento\Framework\Filesystem\Directory\Read
$mediaDirectory */
$mediaDirectory = $this->_objectManager-
>get('Magento\Framework\Filesystem')
->getDirectoryRead(DirectoryList::MEDIA);
$result = $uploader->save(
$mediaDirectory
->getAbsolutePath('Bootsgrid/Productlabel')
);
//$data['profile'] = 'Modulename/Profile/'. $result['file'];
$model->setProimage('Bootsgrid/Productlabel'.$result['file']); /
/Database field name
} catch (\Exception $e) {
if ($e->getCode() == 0) {
$this->messageManager->addError($e->getMessage());
}
}
}
$formData = $this->getRequest()->getParam('label');
$model->setData($formData);
try {
// Save news
$model->save();
// Display success message
$this->messageManager->addSuccess(__('The post has been
saved.'));
// Check if 'Save and Continue'
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', ['id' => $model->getId(),
'_current' => true]);
return;
}
// Go to grid page
$this->_redirect('*/*/');
return;
} catch (\Exception $e) {
$this->messageManager->addError($e->getMessage());
}
$this->_getSession()->setFormData($formData);
$this->_redirect('*/*/edit', ['id' => $postId]);
}
}
}