Note: I am not using UI component
I have a file Grid.php
where I have a column image
, in this column, image URL is populating
I want to show the image in this column instead of image URL
Note: I am not using UI component
I have a file Grid.php
where I have a column image
, in this column, image URL is populating
I want to show the image in this column instead of image URL
I have figured out the solution of this:
In my Grid.php
I have used 'frame_callback' function like this:
$this->addColumn(
'image',
[
'header' => __('Image'),
'index' => 'image',
'type' => 'image',
'frame_callback' => array($this, 'show_image'),
]
);
After this, I have added show_image
function at the end of the file:
public function show_image($value)
{
if (empty($value)){
return '';
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$mediaUrl = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$width = 150;
return "<img src='" . $mediaUrl . $value . "' width='" . $width . "'/>";
}
After this, image is now appearing on my custom grid.
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;
}
}
frame_callback
function and it is working fine for me. But it could also be done through renderer that you have mentioned. Thanks for the effort. +1
Commented
Apr 10, 2019 at 11:15