Add new column into InstallSchema.php for image
->addColumn(
'img',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
['nullable' => true],
'Image'
)
Add Form type must be this
enctype="multipart/form-data" : No characters are encoded. This value is required when you are using forms that have a file upload control.
$form = $this->_formFactory->create(
['data' => [
'id' => 'edit_form',
'enctype' => 'multipart/form-data',
'action' => $this->getData('action'),
'method' => 'post'
]
]
);
Add field into your form
$fieldset->addField(
'img',
'image',
[
'name' => 'img',
'label' => __('Upload Image'),
'title' => __('Upload Image'),
'required' => true,
'note' => 'Allow image type: jpg, jpeg, png',
'class' => 'required-entry required-file',
]
);
For Save Image
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();
/* for delete image */
if (isset($data['img']['delete'])) {
if ($data['img']['delete'] == 1) {
$data['img'] = '';
}
}
/* for upload image */
if ((isset($_FILES['img']['name'])) && ($_FILES['img']['name'] != '') && (!isset($data['img']['delete']))) {
try
{
$uploaderFactory = $this->uploaderFactory->create(['fileId' => 'img']);
$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('Vendorename_ModuleName_IMG');
//echo "<br/>destination path".$destinationPath;
$result = $uploaderFactory->save($destinationPath);
// print_r($result);
if (!$result) {
throw new LocalizedException
(
__('File cannot be saved to path: $1', $destinationPath)
);
}
$imagePath = 'Vendorename_ModuleName_IMG' . $result['file'];
//echo "<br/> Image store ".$imagePath;
$data['img'] = $imagePath;
} // try block
catch (\Exception $e) {
$this->messageManager->addError(__("Image not Upload Pleae Try Again"));
}
}
.............................................
.............................................
echo "<pre>";
print_r($data)
exit();
}
}
For show image into Grid
<column name="img" class="Vendorename\Modulename\Ui\Component\Listing\Column\Thumbnail">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
<item name="sortable" xsi:type="boolean">false</item>
<item name="altField" xsi:type="string">store image</item>
<item name="has_preview" xsi:type="string">1</item>
<item name="filter" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Image</item>
<item name="sortOrder" xsi:type="number">80</item>
</item>
</argument>
</column>
Vendorename\Modulename\Ui\Component\Listing\Column
Thumbnail.php
<?php
namespace Vendorename\Modulename\Ui\Component\Listing\Column;
use Magento\Catalog\Helper\Image;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\Component\Listing\Columns\Column;
class Thumbnail extends Column
{
const ALT_FIELD = 'title';
protected $storeManager;
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
Image $imageHelper,
UrlInterface $urlBuilder,
StoreManagerInterface $storeManager,
array $components = [],
array $data = []
) {
$this->storeManager = $storeManager;
$this->imageHelper = $imageHelper;
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if(isset($dataSource['data']['items'])) {
$fieldName = $this->getData('name');
foreach($dataSource['data']['items'] as & $item) {
$url = '';
if($item[$fieldName] != '') {
$url = $this->storeManager->getStore()->getBaseUrl(
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
).$item[$fieldName];
}
$item[$fieldName . '_src'] = $url;
$item[$fieldName . '_alt'] = $this->getAlt($item) ?: '';
$item[$fieldName . '_link'] = $this->urlBuilder->getUrl('routename/controllername/actionname',['id' => $item['id']]);
$item[$fieldName . '_orig_src'] = $url;
}
}
return $dataSource;
}
protected function getAlt($row)
{
$altField = $this->getData('config/altField') ?: self::ALT_FIELD;
return isset($row[$altField]) ? $row[$altField] : null;
}
}
Run Magento command
php bin/magento s:up
php bin/magento c:c
I Hope This Helps You.