1

I want to show uploaded image in admin form. I use this code to upload image in admin form.

$fieldset->addField(
    'image',
    'image',
    [
        'name' => 'image',
        'label' => __('Image'),
        'title' => __('Image'),
        'required' => false,
        'disabled' => $isElementDisabled
    ]
);
  • Let me know if you have any issue – Prince Patel Dec 26 '17 at 11:52
0

Add addType() in admin form

 $fieldset->addType(
        'image',
        '\Vendor\Module\Block\Adminhtml\Flip\Renderer\Image'
        );

Now create renderer block(Image.php) at

Vendor\Module\Block\Adminhtml\Flip\Renderer

Copy this code

<?php

namespace Vendor\Module\Block\Adminhtml\Flip\Renderer;

class Image extends \Magento\Framework\Data\Form\Element\Image
{
    protected function _getUrl()
    {   
        $url = 'book'.$this->getValue(); // book is image directory
        return $url;
    }
}

Now you can see image on admin form.

| improve this answer | |
0

First add this code into your Form Block File

Form.php

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

Now Change your Form Save Controller File to Save your Image File.

Save.php

      <?php

      namespace [vendorname]\[modulename]\Controller\Adminhtml\locator;

      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'];

                  // store image path in database table 

                   $data['image'] = $imagePath;


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

                }

            } 

            else if (isset($data['id'])) 
            {
              if((isset($data['image']['delete']) && $data['image']['delete'] == 1))
              {
                  // for image delete 

                $data['image'] = null;
                $this->messageManager->addSuccess(__('Image Deleted'));
              }

            } 

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


         /* for save data */

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

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

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

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

        }

      }

Make a sure your image field in the table field must be 'nullable'=> true because image delete make this field's null. if it is not null then image delete operation not work because not null fields must have a value.

InstallSchema.php

  ->addColumn(
              'image',
              \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
              255,
              ['nullable' => false],
              'Image'
          )

I Hope This Helps You.

| improve this answer | |
  • if you have any problem related to this solution you can comment here i will help you to find solution of your problem – Msquare Sep 20 '19 at 3:10
  • If it's works for you VOTE UP – Msquare Oct 13 '19 at 5:54

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.