when a edit admin form, Previously saved image path become blank in db how to solve this problem in magento 2 I m done a image upload and save into db by using this code
- In form upload and save a image in database
Please someone help me solve this issue
Updated Controller file: Save.php
<?php
namespace Cm\Productlabel\Controller\Adminhtml\Label;
use Magento\Backend\App\Action;
use Magento\Framework\App\Filesystem\DirectoryList;
class Save extends Action
{
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()->getPostValue();
$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);
}
$formData = $this->getRequest()->getParam('label');
if(!empty($post['proimage']['value']))
{
$imageName = $post['proimage']['value'];
$post['proimage'] = $imageName;
}
$model->setData($formData);
$imagePost = $this->getRequest()->getFiles('proimage');
$fileName = ($imagePost && array_key_exists('name', $imagePost)) ? $imagePost['name'] : null;
if($imagePost && $fileName) {
try {
$uploader = $this->_objectManager->create(
'Magento\MediaStorage\Model\File\Uploader',
['fileId' => 'proimage']
);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$imageAdapterFactory = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')
->create();
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
->getDirectoryRead(DirectoryList::MEDIA);
$result = $uploader->save(
$mediaDirectory
->getAbsolutePath('Cm/Productlabel')
);
$model->setProimage('Cm/Productlabel'.$result['file']);
} catch (\Exception $e) {
if ($e->getCode() == 0) {
$this->messageManager->addError($e->getMessage());
}
}
}
try {
// var_dump($model->setProimage( $prev_img ));exit; // before saving
$model->save();
// Display success message
$this->messageManager->addSuccess(__('The label 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]);
}
}
}