Question

I have added a custom admin grid using ui component, now I want to add a thumbnail field in the grid. Please help me to do the same..

Was it helpful?

Solution

Add below column code in your ui_component

<column name="image" class="Vendor\Module\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="has_preview" xsi:type="string">1</item>                    
                    <item name="label" xsi:type="string" translate="true">Slider Image</item>
                </item>
            </argument>
        </column>

Thumbnail class add code at Vendor\Module\Ui\Component\Listing\Column\Thumbnail.php as below

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\Module\Ui\Component\Listing\Column;

use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;

class Thumbnail extends \Magento\Ui\Component\Listing\Columns\Column
{
    protected $storeManager;

    /**
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param \Magento\Catalog\Helper\Image $imageHelper
     * @param \Magento\Framework\UrlInterface $urlBuilder
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        StoreManagerInterface $storeManager,
        array $components = [],
        array $data = []
    ) {
        parent::__construct($context, $uiComponentFactory, $components, $data);
        $this->storeManager = $storeManager;
    }

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        if(isset($dataSource['data']['items'])) {
            $fieldName = $this->getData('name');
            $path = $this->storeManager->getStore()->getBaseUrl(
                        \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                    );
            foreach ($dataSource['data']['items'] as & $item) {               
                $item[$fieldName . '_src'] = $path.$item['image'];
                $item[$fieldName . '_alt'] = $item['slider_title'];
                $item[$fieldName . '_orig_src'] = $path.$item['image'];
            }
        }

        return $dataSource;
    }   
}

In above code change field name as per your field

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top