Add custom column to admin grid for your module. we will see how to add a banner image column to our grid.
For example our module name will be Magento_Banner.
Adding Banner Image to Grid
Open your Grid.php file and add the code in the _prepareColumns() function of your module
we need to create this Block. The code inside this block is as follows:
then in our renderer we can use
$this->getColumn()->getAttr1()
You can also access the data of the current row using the $row variable passed in the render function, for example the below code will show the path of image as well.
For example our module name will be Magento_Banner.
Adding Banner Image to Grid
Open your Grid.php file and add the code in the _prepareColumns() function of your module
$this->addColumn('image', array( 'header' => Mage::helper('banner')->__('Banner Image'), 'align' =>'left', 'index' => 'bannerimage', 'renderer' => 'banner/adminhtml_banner_renderer_image' ));Here we have specified an renderer block type as ‘banner/adminhtml_banner_renderer_bannerimage’.
we need to create this Block. The code inside this block is as follows:
<?php class Magento_Banner_Block_Adminhtml_Banner_Renderer_BannerImage extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract{ public function render(Varien_Object $row) { $html = '<img '; $html .= 'id="' . $this->getColumn()->getId() . '" '; $html .= 'src="' . $row->getData($this->getColumn()->getIndex()) . '"'; $html .= 'class="grid-image ' . $this->getColumn()->getInlineCss() . '"/>'; return $html; } }This is all that is needed, if you open your grid you show see an image there. You have to adjust path/src of the image to make it show correctly. Here the $this->getColumn() function is the important function, you can access the array you pass in the Grid.php file in the getColumn() function. For example, if we write in Grid.php file
$this->addColumn('image', array( 'header' => Mage::helper('banner')->__('Banner Image'), 'align' =>'left', 'index' => 'image', 'renderer' => 'banner/adminhtml_banner_renderer_bannerimage', 'attr1' => 'value1' ));
then in our renderer we can use
$this->getColumn()->getAttr1()
You can also access the data of the current row using the $row variable passed in the render function, for example the below code will show the path of image as well.
class Magento_Banner_Block_Adminhtml_Banner_Renderer_BannerImage extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract{ public function render(Varien_Object $row) { $html = '<img '; $html .= 'id="' . $this->getColumn()->getId() . '" '; $html .= 'src="' . $row->getData($this->getColumn()->getIndex()) . '"'; $html .= 'class="grid-image ' . $this->getColumn()->getInlineCss() . '"/>'; $html .= '<br/><p>'.$row->getData($this->getColumn()->getIndex()).'</p>'; return $html; } }
How can we apply filters on new column! thanks
ReplyDeleteGood post! will get my hands on it
ReplyDelete