1

I'm using Magento 2.3.4 to create a custom form this form I created is generated using generic form not the UiComponent form ,in this form i need to be able to up How to add an image input to Magento 2 generic form?

    $fieldset->addField(
        'title',
        'file',
        ['image' => 'title', 'label' => __('Image'), 'title' => __('Image'), 'required' => true]
    );
1

1 Answer 1

2

Add this for image field

$fieldset->addField(
        'img_name',
        'image', 
        [
            'name' => 'img_name',
            'label' => __('Upload Image'),
            'title' => __('Upload Image'),
            'required' => true,
            'note' => 'Allow image type: jpg, jpeg, png',
            'class' => 'required-entry required-file',
        ]
    );

And your form must be have enctype="multipart/form-data" attribute.

    $form = $this->_formFactory->create(
        ['data' => [
                        'id' => 'edit_form',
                        'enctype' => 'multipart/form-data',
                        'action' => $this->getData('action'),
                        'method' => 'post'
                    ]
        ]
    );

And image can be save using below code in your controller (code is only for save image not all form data)

protected $fileSystem;
protected $uploaderFactory;
protected $adapterFactory;


public function __construct(
    ............................................................
    ............................................................

    \Magento\Framework\Filesystem $fileSystem,
    \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
    \Magento\Framework\Image\AdapterFactory $adapterFactory
    ............................................................
    ............................................................

) {
    ............................................................
    ............................................................

    $this->fileSystem = $fileSystem;
    $this->adapterFactory = $adapterFactory;
    $this->uploaderFactory = $uploaderFactory;

    ............................................................
    ............................................................
}

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

    if ( (isset($_FILES['img_name']['name'])) && ($_FILES['img_name']['name'] != '')) 
      {
        try 
           {    
             $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'img_name']);
             $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
             $imageAdapter = $this->adapterFactory->create();
             $uploaderFactory->setAllowRenameFiles(true);
             $uploaderFactory->setFilesDispersion(true);
             $mediaDirectory = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA);
             $destinationPath = $mediaDirectory->getAbsolutePath('Your_FILE_PATH');
             $result = $uploaderFactory->save($destinationPath);
             if (!$result) 
                   {
                     throw new LocalizedException
                     (
                        __('File cannot be saved to path: $1', $destinationPath)
                     );

                   }
            $data['img_name'] = 'Your_FILE_PATH'.$result['file'];
           } 
           catch (\Exception $e) 
          {   
              $this->messageManager->addError(__("Image not Upload Pleae Try Again")); 
              $this->_redirect('*/*/index');
              return;
          }
      }
      echo "<pre>";
      print_r($data);
      exit();
      ....................................................
      ....................................................

}

I Hope This Helps You.

4
  • Hi @Masquare thanks it's working, in the controller can we resize the image height and width using uploader class?
    – jojo
    Mar 26, 2020 at 1:45
  • @jojo yes we can resize images
    – Msquare
    Mar 26, 2020 at 3:14
  • how to resize it?
    – jojo
    Mar 26, 2020 at 3:21
  • Try this link magento.stackexchange.com/questions/134360/…
    – Msquare
    Mar 26, 2020 at 3:25

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.