How to use renderer class in magento 2 admin Grid:

Renderer class will useful to return the customized value for admin grid.
Ex: In my admin form grid , I want to show some customized result instead of actual database column value.In that case we can use renderer class for our customized result. Below script will return/display the result of image, instead of image path (in my DB table column (Sample Column name is image_path) maintain Image path as value)

Script: 1 Admin Grid, below is my admin grid file path.
File path: Jute\Ecommerce\Block\Adminhtml\Image.php
 protected function _prepareColumns()  {
 $this->addColumn(
 'image',
 [
 'header' => __('Image'),
 'index' => 'image_path',
 'filter' => false,
 'class' => 'xxx',
 'width' => '50px',
 'renderer' => '<MYMODULEPATH>\Block\Adminhtml\Helper\Renderer\<FILENAME>',
 ] );
 }
Script: 2
Customized Your renderer file according to your requirement. 
Here am returning the image instead of image path.
Below is my renderer file path,
File path: Jute\Ecommerce\Block\Adminhtml\Helper\Renderer\Image.php
<?php
namespace Jute\Ecommerce\Block\Adminhtml\Helper\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)  {
 $row->getId() ///wil get primarykey value.
 $storeViewId = $this->getRequest()->getParam('store');
 /** @var \Jute\Ecommerce\Model\ResourceModel\Collection $collection */
 $imageObj = $this->_myCollectionFactory->create()->setStoreViewId($storeViewId)->load($row->getId());
 $srcImage = $this->_storeManager->getStore()->getBaseUrl(
 \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
 ) . $imageObj->getImagePath();
return '<image width="150" height="50" src ="'.$srcImage.'" alt="'.$imageObj->getImage().'" >';
 }
}

Leave a Reply