0

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]);
          }
       }

    }
3

1 Answer 1

3

Add Below code in n _prepareForm() function inside

app/code/Vendor/Module/Block/Adminhtml/Module/Edit/Tab/Main.php

$fieldset->addField(
    'profile',
    'image',
    [
        'name' => 'profile',
        'label' => __('Profile Image'),
        'title' => __('Profile Image'),
        'required'  => false,
        'disabled' => $isElementDisabled
    ]
);

Now in execute() method of your save controller file. use below code to save and upload image.

app/code/Vendor/Module/Controller/Adminhtml/Index/Save.php

use Magento\Framework\App\Filesystem\DirectoryList;

$profileImage = $this->getRequest()->getFiles('profile');
$fileName = ($profileImage && array_key_exists('name', $profileImage)) ? $profileImage['name'] : null;
if ($profileImage && $fileName) {
    try {
        /** @var \Magento\Framework\ObjectManagerInterface $uploader */
        $uploader = $this->_objectManager->create(
            'Magento\MediaStorage\Model\File\Uploader',
            ['fileId' => 'profile']
        );
        $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('Modulename/Profile')
        );
        //$data['profile'] = 'Modulename/Profile/'. $result['file'];
        $model->setProfile('Modulename/Profile'.$result['file']); //Database field name
    } catch (\Exception $e) {
        if ($e->getCode() == 0) {
            $this->messageManager->addError($e->getMessage());
        }
    }
}

And Image showing in grid follow this link : Reference

13
  • when i save a image, in save.php controller file i get a null value prnt.sc/nag0sd @rakesh Apr 11, 2019 at 9:06
  • i used a var_dump() function it reflects null prnt.sc/nag2ni @rakesh Apr 11, 2019 at 9:06
  • its not working Apr 11, 2019 at 10:46
  • @divyasekar it is working code i have many time used you are small mistake any where Apr 11, 2019 at 10:50
  • wait i will post a code Apr 11, 2019 at 10:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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