How to Display an Image Thumbnail in Admin Grid in Magento 2
In one of the previous post, we have seen how to add an image upload field in admin form. However to display that image in admin grid listing, we have to write some extra lines of code. Let’s see.
Display an Image Thumbnail in Admin Grid in Magento 2
In you admin grid file codextblog_demo_listing.xml
add below code.
<column name="icon" component="Magento_Ui/js/grid/columns/thumbnail" class="Codextblog\Demo\Ui\Component\Listing\Column\Image"> <settings> <label translate="true">Icon</label> <hasPreview>1</hasPreview> <sortable>false</sortable> </settings> </column>
You can see that we have defined Image class to render an image. Create Image.php
file under app/code/Codextblog/Demo/Ui/Component/Listing/Column
. Add below code in that file.
<?php namespace Codextblog\Demo\Ui\Component\Listing\Column; use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Store\Model\StoreManagerInterface; use Magento\Ui\Component\Listing\Columns\Column; class Image extends Column { const URL_PATH_EDIT = 'codextblog_demo/demo/edit'; /** * @var StoreManagerInterface */ protected $storeManager; /** * @var UrlInterface */ protected $url; /** * Image constructor. * @param ContextInterface $context * @param UiComponentFactory $uiComponentFactory * @param StoreManagerInterface $storeManager * @param UrlInterface $url * @param array $components * @param array $data */ public function __construct( ContextInterface $context, UiComponentFactory $uiComponentFactory, StoreManagerInterface $storeManager, UrlInterface $url, array $components = [], array $data = [] ) { parent::__construct($context, $uiComponentFactory, $components, $data); $this->storeManager = $storeManager; $this->url = $url; } public function prepareDataSource(array $dataSource) { $mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA); if (isset($dataSource['data']['items'])) { $fieldName = 'icon'; foreach ($dataSource['data']['items'] as & $item) { if (!empty($item['icon'])) { $name = $item['icon']; $item[$fieldName . '_src'] = $mediaUrl.'codextblog/demo/'.$name; $item[$fieldName . '_alt'] = ''; $item[$fieldName . '_link'] = $this->url->getUrl(static::URL_PATH_EDIT, [ 'id' => $item['id'] ]); $item[$fieldName . '_orig_src'] = $mediaUrl.'codextblog/demo/'.$name; } } } return $dataSource; } }
In line no. 49 we have defined the image field name “icon”. In line no. 53 and 58 we have defined the directory path where image is actually uploaded. If you don’t know what path to add over there, then follow this post.
If everything works well, then you will see image thumbnail in your admin grid. Upon click of that thumbnail, popup will open. That popup will display actual image.
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me