How To

How to Display Image in Custom Module using Form Field in Magento 2

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

Click to rate this post!
[Total: 19 Average: 4.3]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

14 hours ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

6 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

6 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

7 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago