Monday, June 24, 2013

How to add multi-select attribute in Admin product Grid view


Here I've shown a multi-select attribute named "brand".

>> In admin Grid.php find the method "_prepareColumns()" add the following code:

        $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'brand');        // attribute code here
        foreach ( $attribute->getSource()->getAllOptions(true, true) as $option)
        {
            if($option['value'] != '')
            $valArr[$option['value']] =  $option['label'];
        }
        // above code will use to show the dropdown
       
        $this->addColumn('brand',
            array(
                'header'=> Mage::helper('catalog')->__('Brands'),
                'width' => '60px',
                'index' => 'brand',
                'type'  => 'options',
                'options' => $valArr,
                'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands', // Will have to create the renderer.
                'filter_condition_callback' => array($this, '_filterBrandCondition')
        ));
       
        Then in this page you need to define the method "_filterBrandCondition" to filter with selected item.
       
        protected function _filterBrandCondition($collection, $column)
        {
            if (!$value = $column->getFilter()->getValue()) {
                return;
            }
            $this->getCollection()->addFieldToFilter('brand', array('finset' => $value));
        }
       
       
>> Now create the Brands.php file in code/local/Mage/Adminhtml/Block/Catalog/Product/Renderer directory and use the following code:

        class Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
        {
            public function render(Varien_Object $row)
            {
                $brands = explode(',',$row->getBrand());
                $html = "";
                if(count($brands)>0)
                {
                    $html ="<ul>";
                    foreach($brands as $value)
                    {
                        $_productModel = Mage::getModel('catalog/product');
                        $attribute = $_productModel->getResource()->getAttribute("brand");
                        if ($attribute ->usesSource()) {
                            $html .= "<li>".$attribute ->getSource()->getOptionText("$value")."</li>";
                        }
                    }
                    $html .= "</ul>";
                }
                return $html ;
            }
        }
       
 cheer :-)


No comments:

Post a Comment