Magento 2 provides upload, store, and retrieve images. Here we learn how to display image in admin UI grid in Magento 2. After add and store images in the file system and values are stores at DB, Now we need to display the image in the admin Ui grid.
If you don’t know about Ui Admin Grid then click here.
Follow the below steps to display the image in the admin UI 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> .....
Here img is column name where image name is saved, And image comes from Thumbnail class.
<?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 { 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] != '') { /* Set your image physical path here */ $url = $this->storeManager->getStore()->getBaseUrl( \Magento\Framework\UrlInterface::URL_TYPE_MEDIA ).$item[$fieldName]; } $item[$fieldName . '_src'] = $url; $item[$fieldName . '_alt'] = $item[$fieldName]; $item[$fieldName . '_link'] = $this->urlBuilder->getUrl('adminRouteName/adminControllerName/actionName',['id' => $item['id']]); // add edit url $item[$fieldName . '_orig_src'] = $url; } } return $dataSource; } }
After adding the above files run PHP bin/magento cache:clean Magento command and refresh your grid. Now you can see images in the admin UI grid.
I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.