How to render an image in Magento 2 Adminhtml grids
To render image in Magento 2 Adminhtml grids, first of all you have to add a grid column with a renderer block name as a parameter:
1 2 3 4 5 6 7 8 |
$this->addColumn( 'image', array( 'header' => __('Image'), 'index' => 'image', 'renderer' => '\Ktpl\Inquiry\Block\Adminhtml\Inquiry\Grid\Renderer\Image', ) ); |
Then it is necessary to create a renderer block as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
namespace Ktpl\Inquiry\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"/>'; } } |
Source (
More Magento 2 tips from the Cookbook