1

I am learning Magento2 and while developing module i got stuck and need help in below 2 points.

1) I have created admin form with Image upload functionality and its working perfectly. but i want to display image in edit form when image is saved. So how to achieve that.

2) Also i want to know how to show image delete checkbox in edit form.

Note: please note that i have created admin form using layout method not ui-component.

code screen shots are attached. any help would be very appreciable.

[1]: https://i.stack.imgur.com/Dlga2.png [code snippet ]

[1]: https://i.stack.imgur.com/T5nDH.png [expecting result like this, or any alternate way to achieve this]

  • The preview link and delete box should appear automatically if the image is saved correctly. check your save function and the location of the saved image. – subroutines Jul 31 '18 at 0:22
  • Thanks for the clue @subroutine. But i found the issue. Issue was with the name of image field. i change name from image_url to image, its working. But what if we have multiple images on same form, that time name should be unique, so how to handle in such case. – Nits Jul 31 '18 at 4:53
  • just give them different names and save them in your module's Adminhtml save controller. – subroutines Jul 31 '18 at 22:36
0

You can Add This

Add this code into From creation file

    $fieldset->addField(
        'image',
        'image', 
            array(
                    'label'     => 'Image',
                    'required'  => false,
                    'name'      => 'image',  
                    'note' => 'Allow image type: jpg, jpeg, png',      
                    )
    );

Add This code into your Save From Data File

<?php


  namespace [vendor_Name]\[Module_name]\Controller\Adminhtml\[controller_name];

  use Magento\Backend\App\Action;
  use Magento\Framework\App\Filesystem\DirectoryList;
  use Magento\Framework\Exception\LocalizedException;
  use Magento\Framework\Filesystem;
  use Magento\MediaStorage\Model\File\UploaderFactory;
  use Magento\Framework\Image\AdapterFactory;


  class Save extends \Magento\Backend\App\Action
  {

      protected $fileSystem;

      protected $uploaderFactory;

      protected $request;

      protected $adapterFactory;


      public function __construct(
          \Magento\Backend\App\Action\Context $context,
          \Magento\Framework\Filesystem $fileSystem,
          \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
          \Magento\Framework\App\RequestInterface $request,
          AdapterFactory $adapterFactory
      ) {
          parent::__construct($context);
          $this->fileSystem = $fileSystem;
          $this->request = $request;
          $this->adapterFactory = $adapterFactory;
          $this->uploaderFactory = $uploaderFactory;
      }

      public function execute()
      { 
        $data = $this->getRequest()->getPostValue();


        if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') 
        {

           try 
             {    

               $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'image']);
               $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
               $imageAdapter = $this->adapterFactory->create();
               $uploaderFactory->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
               $uploaderFactory->setAllowRenameFiles(true);
               $uploaderFactory->setFilesDispersion(true);

               $mediaDirectory = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA);
               $destinationPath = $mediaDirectory->getAbsolutePath('[Folder_name]');


               $result = $uploaderFactory->save($destinationPath);


               if (!$result) 
                     {
                       throw new LocalizedException
                       (
                          __('File cannot be saved to path: $1', $destinationPath)
                       );

                     }

               $imagePath = '[Folder_Name]'.$result['file'];


               $data['image'] = $imagePath;


             } 
             catch (\Exception $e) 
            {   
                 $this->messageManager->addError(__($e->getMessage()));

            }

        } 

      else
        {     
              $this->messageManager->addError(__("Image not Save Pleae Try Again")); 
              $this->_redirect('*/*/index');
              return;
        }


           if (!$data and $data['image'] == '') 
            {    
                $this->messageManager->addError(__("Data Not Save Pleae Try Again")); 
                $this->_redirect('*/*/index');
                return;
            }

                try {
                        $rowData = $this->_objectManager->create('[vendor_Name]\[Module_name]\Model\locator');
                        $rowData->setData($data);

                        if (isset($data['id'])) 
                        {
                            $rowData->setId($data['id']);
                            $rowData->setStoreImage($data['image']);
                        }
                        $rowData->save();

                        $this->messageManager->addSuccess(__('Data has been successfully saved.'));
                      } 
                  catch (\Exception $e) 
                      {
                          $this->messageManager->addError(__($e->getMessage()));
                      }

            $this->_redirect('*/*/index');




          }


      }

I Hope This Helps You.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.