In admin form after edit and save a form in db, already stored image save as blank in db in magento 2

The question:

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

  1. In form upload and save a image in database

enter image description here

  1. after edit and save a form again, image will be blank
    enter image description here

Please someone help me solve this issue

Updated
Controller file: Save.php

<?php

namespace CmProductlabelControllerAdminhtmlLabel;
use MagentoBackendAppAction;
use MagentoFrameworkAppFilesystemDirectoryList;

class Save extends Action
{

    public function __construct(
      ActionContext $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('CmProductlabelModelProductlabel');
         $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(
            'MagentoMediaStorageModelFileUploader',
            ['fileId' => 'proimage']
        );
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
        $imageAdapterFactory = $this->_objectManager->get('MagentoFrameworkImageAdapterFactory')
            ->create();
        $uploader->setAllowRenameFiles(true);
        $uploader->setFilesDispersion(true);
        $uploader->setAllowCreateFolders(true);
        $mediaDirectory = $this->_objectManager->get('MagentoFrameworkFilesystem')
            ->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]);
      }
   }

}

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Just add these two line before $model->setData($formData);

if(!empty($post['proimage']['value']))
{
    $imageName = $post['proimage']['value'];
    $post['proimage'] = $imageName;
}

Method 2

Please check your save controller. If you are validating the image before saving the data.

if (isset($data['proimage'][0]['name']) && isset($data['proimage'][0]['tmp_name'])) {
            $data['proimage'] ='/banners/'.$data['proimage'][0]['name'];
        } elseif (isset($data['proimage'][0]['name']) && !isset($data['image'][0]['tmp_name'])) {
            $data['proimage'] =$data['proimage'][0]['name'];
        } else {
            $data['proimage'] = null;
        }
 $model->setData($data);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment