25

I want to display an image in the admin grid of one of my modules.
I'm using the new grid system, the one with ui components.
I took a look at how the thumbnail is added in the grid for products, but it's kind of over my head.
My entity is not EAV, is a simple flat table entity.
I tried adding this in my ui component xml file

<column name="image">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/image</item>
            <item name="sortable" xsi:type="boolean">false</item>
            <item name="altField" xsi:type="string">name</item>
            <item name="has_preview" xsi:type="string">1</item>
            <item name="label" xsi:type="string" translate="true">Image</item>
        </item>
    </argument>
</column>

but it seams to have no effect on my grid. there is no image (my db field is called image) column, no error, no nothing.
Can someone walk me through adding an image to the grid using ui components?

4 Answers 4

36

Your ui component xml should have this added:

<column name="image" class="Your\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">title</item>
            <item name="has_preview" xsi:type="string">1</item>
            <item name="label" xsi:type="string" translate="true">Thumbnail</item>
        </item>
    </argument>
</column>

..and then in Your\Modulename\Ui\Component\Listing\Column\Thumbnail.php something similar to this:

<?php
namespace Your\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';

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param Image $imageHelper
     * @param UrlInterface $urlBuilder
     * @param StoreManagerInterface $storeManager
     * @param array $components
     * @param array $data
     */
    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);
    }

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    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
                    ).'pathtoyourimage/'.$item[$fieldName];
                }
                $item[$fieldName . '_src'] = $url;
                $item[$fieldName . '_alt'] = $this->getAlt($item) ?: '';
                $item[$fieldName . '_link'] = $this->urlBuilder->getUrl(
                    'your_module/yourentity/edit',
                    ['yourentity_id' => $item['yourentity_id']]
                );
                $item[$fieldName . '_orig_src'] = $url;
            }
        }

        return $dataSource;
    }

    /**
     * @param array $row
     *
     * @return null|string
     */
    protected function getAlt($row)
    {
        $altField = $this->getData('config/altField') ?: self::ALT_FIELD;
        return isset($row[$altField]) ? $row[$altField] : null;
    }
}

I hope that helps!

5
  • This helped me out! I had to change a couple of lines though. I changed if($item[$fieldName] != '') to if($item['url'] != '') and 'pathtoyourimage/'.$item[$fieldName] to 'pathtoyourimage/'.$item['url']. My $fieldName was returning 'image' however my db field was called 'url'. The rest of the $item[$fieldName . '***'] were left in place. Nov 30, 2017 at 8:41
  • Thanks, @MageDevNL. what if I'd want to show multiple images when we click on the thumbnail image. Dec 22, 2017 at 10:20
  • perfect its work good . Image shown ! But now i wnat to append some text with Image . I try but not usefulll . Can you tell me how text append with image . i just want to show product image and in new line product sku and name
    – HaFiz Umer
    Sep 21, 2019 at 19:44
  • Perfect ! it work good ! how can we append some text with Image . I have show product image and now want to append sku and name on new line of image with same column . can you tell me how append some text with Image ?
    – HaFiz Umer
    Sep 21, 2019 at 21:04
  • @MageDevNL Can you please explain what is yourentity and yourentity_id ? Dec 2, 2020 at 7:26
7

In your grid.php define like below

$this->addColumn(
    'image',
    array(
        'header' => __('Image'),
        'index' => 'image',
        'renderer'  => '\Vendorname\Modulename\Block\Adminhtml\Modulename\Grid\Renderer\Image',
    )
);

Create Image.php under

\Vendorname\Modulename\Block\Adminhtml\Modulename\Grid\Renderer\

and paste below code

namespace Vendorname\Modulename\Block\Adminhtml\Modulename\Grid\Renderer;

class Image extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer
{
    protected $_storeManager;


    public function __construct(
        \Magento\Backend\Block\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,      
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_storeManager = $storeManager;        
    }


    public function render(\Magento\Framework\DataObject $row)
    {
        $img;
        $mediaDirectory = $this->_storeManager->getStore()->getBaseUrl(
           \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
       );
        if($this->_getValue($row)!=''):
            $imageUrl = $mediaDirectory.$this->_getValue($row);
            $img='<img src="'.$imageUrl.'" width="100" height="100"/>';
        else:
            $img='<img src="'.$mediaDirectory.'Modulename/no-img.jpg'.'" width="100" height="100"/>';
        endif;
        return $img;
    }
}
2
  • 1
    I think you didn't understand the question right. My grid is build using UI-components. This does not work with UI-components.
    – Marius
    Jun 12, 2017 at 7:14
  • 3
    this answer helped me to my work without using UI - components
    – Mujahidh
    Oct 26, 2017 at 9:30
4

Just add this tag in you ui_component layout file

<column name="logo" class="NAMESPACE\MODULENAME\Ui\Component\Listing\Columns\Logo">
    <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="add_field" xsi:type="boolean">true</item>-->
            <item name="sortable" xsi:type="boolean">false</item>
            <item name="altField" xsi:type="string">name</item>
            <item name="has_preview" xsi:type="string">1</item>
            <item name="label" xsi:type="string" translate="true">Brand Logo</item>
        </item>
    </argument>
</column>

and create this new file which we have assign in our ui_component column

<?php
namespace NAMESPACE\MODULENAME\Ui\Component\Listing\Columns;

use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;

class Logo extends \Magento\Ui\Component\Listing\Columns\Column
{
    const NAME = 'logo';

    const ALT_FIELD = 'name';

    protected $_storeManager;

    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,        
        \Magento\Framework\UrlInterface $urlBuilder,
        array $components = [],
        array $data = [],
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {        
        parent::__construct($context, $uiComponentFactory, $components, $data);
        $this->_storeManager = $storeManager;
        $this->urlBuilder = $urlBuilder;
    }

    /**
    * Prepare Data Source
    *
    * @param array $dataSource
    * @return array
    */
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            $fieldName = $this->getData('name');
            foreach ($dataSource['data']['items'] as & $item) {
                $mediaRelativePath=$this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
                $logoPath=$mediaRelativePath.$item['logo'];
                $item[$fieldName . '_src'] = $logoPath;
                $item[$fieldName . '_alt'] = $this->getAlt($item);
                $item[$fieldName . '_link'] = $this->urlBuilder->getUrl(
                    'brand/manage/edit',
                    ['brand_id' => $item['brand_id'], 'store' => $this->context->getRequestParam('store')]
                );
                $item[$fieldName . '_orig_src'] = $logoPath;

            }
        }

        return $dataSource;
    }

    /**
    * @param array $row
    *
    * @return null|string
    */
    protected function getAlt($row)
    {
        $altField = self::ALT_FIELD;
        return isset($row[$altField]) ? $row[$altField] : null;
    }
}

In prepareDataSource function you will get each column object.

Hope this will help you.

1
  • Is it possible to give height and width to thumbnail image.. Mar 26, 2019 at 11:47
2

Finally, I have solution for my question. I have added a grid column with renderer block name as parameter.

$this->addColumn(
    'image',
    array(
        'header' => __('Image'),
        'index' => 'image',
        'renderer'  => '\YourVendor\YourModule\Block\Adminhtml\Inquiry\Grid\Renderer\Image',
    )
);

Then I have added created a renderer block as below:

namespace YourVendor\YourModule\Block\Adminhtml\Inquiry\Grid\Renderer;

use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer;
use Magento\Framework\Object;
use Magento\Store\Model\StoreManagerInterface;

class Image extends AbstractRenderer
{
    private $_storeManager;
    /**
     * @param \Magento\Backend\Block\Context $context
     * @param array $data
     */
    public function __construct(\Magento\Backend\Block\Context $context, StoreManagerInterface $storemanager, array $data = [])
    {
        $this->_storeManager = $storemanager;
        parent::__construct($context, $data);
        $this->_authorization = $context->getAuthorization();
    }
    /**
     * Renders grid column
     *
     * @param Object $row
     * @return  string
     */
    public function render(Object $row)
    {
        $mediaDirectory = $this->_storeManager->getStore()->getBaseUrl(
            \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
        );
        $imageUrl = $mediaDirectory.'/inquiry/images'.$this->_getValue($row);
        return '<img src="'.$imageUrl.'" width="50"/>';
    }
}

I hope this will help you.

1
  • 5
    thanks for trying, but you did not pay attention while reading the question. I am trying to use the grid created via ui components not with a grid block as in magento 1.
    – Marius
    Dec 24, 2015 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.