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.