Hello Magento Friends,
Hope all are doing great. Today I will be showing How to Display Image in Custom Module using Form Field in Magento 2. Coincidentally, you missed our previously published blog, How to Add Date & Time Picker in Magento 2 System Configuration With Custom Format.
Generally, in Magento 2 grid form, we can put the image upload field but it will not display in the grid as one column. If you want to display the small image in the grid of your custom extension then you need to follow the below steps.
Let’s get started
Steps to Display Image in Custom Module using Form Field in Magento 2:
Step 1: Add new column into InstallSchema.php for image
->addColumn( 'img', \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 255, ['nullable' => true], 'Image' )
Step 2: Add Form type must be
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' ] ] );
Step 3: 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', ] );
Step 4: For saving the image, place the code at the below path
app/code/Vendor/Extension/controller/saveimage.php
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 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('Vendor_Extension_IMG'); $result = $uploaderFactory->save($destinationPath); if (!$result) { throw new LocalizedException ( __('File cannot be saved to path: $1', $destinationPath) ); } $imagePath = 'Vendor_Extension_IMG' . $result['file']; $data['img'] = $imagePath; } catch (\Exception $e) { $this->messageManager->addError(__("Image not Upload Pleae Try Again")); } } echo "<pre>"; print_r($data) exit(); }
Step 5: For showing the image into Grid, add this code in your grid file.
<column name="img" class="Vendor\Extension\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>
Step 6: Create the file Vendor\Extension\Ui\Component\Listing\Column\Thumbnail.php
<?php namespace Vendor\Extension\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; } }
Step 7: Finally, run the below Magento commands to set up the upgrade and clean cache.
php bin/magento s:up php bin/magento c:c
Conclusion:
Hence, this way it is possible to Display Image in Custom Module using Form Field in Magento 2. Finding difficulty in the implementation of the above code? Simply mention in the comment part and I will be pleased to assist you.
Like it? Share it and do not forget to rate the article with 5 stars. Catch you later till then stay tuned!
Happy Coding
Hi! I have a question, where saveimage.php is used? I dont full understand this part of code.
Thanks!
That is your controller path which saves the data into database.