This article describes how to insert images in the Magento admin product grid.
First of all, you will need to create your own extension. Let’s call it: Atwix_Gridthumbs.
Create a file /app/etc/modules/Atwix_Gridthumbs.xml with this content:
<?xml version="1.0"?> <config> <modules> <Atwix_Gridthumbs> <active>true</active> <codePool>community</codePool> </Atwix_Gridthumbs> </modules> </config>
Next step is the module’s config file. It should be located in /app/code/community/Atwix/Gridthumbs/etc/config.xml. The config file content will be like this:
<?xml version="1.0"?> <config> <modules> <Atwix_Gridthumbs> <version>1.0</version> </Atwix_Gridthumbs> </modules> <global> <blocks> <adminhtml> <rewrite> <catalog_product_grid>Atwix_Gridthumbs_Adminhtml_Block_Catalog_Product_Grid</catalog_product_grid> </rewrite> </adminhtml> </blocks> </global> </config>
Now we need to override standard grid file. Create file /app/code/community/Atwix/Gridthumbs/Adminhtml/Block/Catalog/Product/Grid.php with the following content:
<?php class Atwix_Gridthumbs_Adminhtml_Block_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid { protected function _prepareColumns() { $this->addColumn('image', array( 'header' => Mage::helper('catalog')->__('Image'), 'align' => 'left', 'index' => 'image', 'width' => '70', 'renderer' => 'Atwix_Gridthumbs_Block_Adminhtml_Template_Grid_Renderer_Image' )); return parent::_prepareColumns(); } }
Here you can see line ‘renderer’ => ‘Atwix_Gridthumbs_Block_Adminhtml_Template_Grid_Renderer_Image’ . It says to use the custom renderer for image column. There’s no standard renderer for images, so we need to create it. Create the renderer file /app/code/community/Atwix/Gridthumbs/Block/Adminhtml/Template/Grid/Renderer/Image.php with source:
<?php class Atwix_Gridthumbs_Block_Adminhtml_Template_Grid_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { public function render(Varien_Object $row) { return $this->_getValue($row); } protected function _getValue(Varien_Object $row) { $val = $row->getData($this->getColumn()->getIndex()); $val = str_replace("no_selection", "", $val); $url = Mage::getBaseUrl('media') . 'catalog/product' . $val; $out = "<img src=". $url ." width='60px'/>"; return $out; } }
Renderers return html or just plain text for the cell in the column. You can get the necessary values with the construction $row->getData($this->getColumn()->getIndex());
$this->getColumn()->getIndex(); returns the column index which was entered in addColumn in the previous step. If there is not an image associated with a product, image url will say “no_selection”, so we should remove this string for empty cells with construction $val = str_replace(“no_selection”, “”, $val);
That’s it! To be safe, as will all changes, you should flush cache and log out/log in to be sure you are seeing the new content. Also, don’t forget to optimize your images and import product images from a URL in Magento 2. Happy coding!