Skip to content

Magento2 Admin Grid Product Image Display

I need to display product image in admin grid view. I tried below code.

class Image extends MagentoBackendBlockWidgetGridColumnRendererAbstractRenderer
{ 

public function render(MagentoFrameworkDataObject $row) {


        //$this->helper('MagentoCatalogHelperProduct')->getImageUrl($product);
        //$helper = $this->helper('MagentoCatalogHelperImage')->init($product,'cart_page_product_thumbnail') ->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->setImageFile($product->getImage())->getUrl();

       $id=$row->getId();
       $objectManager = MagentoFrameworkAppObjectManager::getInstance();
       $store = $objectManager->get('MagentoStoreModelStoreManagerInterface')->getStore();
       $product       = $objectManager->get('MagentoCatalogModelProduct')->load($id);


        $imageHelper  = $objectManager->get('MagentoCatalogHelperImage');
        $image_url = $imageHelper->init($product, 'product_thumbnail_image')->setImageFile($product->getFile())->resize(100, 100)->getUrl();
        $prod_name = $product->getName();
       //$product->getDefaultPlaceholderUrl('small_image');
       if($image_url){
        $html='<img class="admin__control-thumbnail" data-bind="attr: {src: $col.getSrc($row()), alt: $col.getAlt($row())}" src="'.$image_url.'" alt="'.$prod_name.'">';
       }
       else{

        $placeholderImageUrl = $imageHelper->getDefaultPlaceholderUrl('thumbnail');
        $html = '<img class="admin__control-thumbnail" data-bind="attr: {src: $col.getSrc($row()), alt: $col.getAlt($row())}" src="'.$placeholderImageUrl.'" alt="'.$prod_name.'">';

       }

        return $html;
    }

}

I am rending this image to grid as follows.

 protected function _prepareColumns()
    {
        $this->addColumn(
            'entity_id',
            [
                'header' => __('ID'),
                'type' => 'number',
                'index' => 'entity_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );
        $this->addColumn('image',
           [
                'header' => __('Image'),
                'type' => 'text',
                'align' => 'center',
                'filter' => false,
                'sortable' => false,
                'renderer' => 'MyModuleBlockAdminhtmlmproductsRendererImage',
            ]);
        $this->addColumn(
            'name',
            [
                'header' => __('Name'),
                'index' => 'name',
            ]
        );
}

I am getting same image for all the products. Whats wrong in my code?