Add categories column to the product grid in Magento admin

Viewed 25833

I'm trying to add a category column to the product grid. I've modified Mage_Adminhtml_Block_Catalog_Product_Grid. Added the following to _prepareCollection :

->joinField('category_ids',
            'catalog/category_product_index',
            'category_id',
            'product_id=entity_id',
            null,
            'left')

which gives me an error : a:5:{i:0;s:72:"Item (Mage_Catalog_Model_Product) with the same id "16243" already exist".

In prepareColumns I'm adding :

$this->addColumn('category_ids',
        array(
            'header'=> Mage::helper('catalog')->__('Categories'),
            'index' => 'category_ids',
            'width' => '150px'
    ));

How can I fix my query so I won't get the error? Is it possible to show and filter by category names instead of ids?

A forum post shows a similar code but I couldn't make it work with categories http://www.magentocommerce.com/boards/viewthread/44534/

static protected $COLUMN_ID_TRADE_REFERENCES = 'ref_text';

protected function _prepareCollection()
{
    $store = $this->_getStore();
    $collection = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('attribute_set_id')
        ->addAttributeToSelect('type_id')
        ->addAttributeToSelect('ref_text')
        ->joinTable('productreferences/reference',
            'product_id=entity_id',
            array('ref_text'),
            null,
            'left')
        ->joinField('qty',
            'cataloginventory/stock_item',
            'qty',
            'product_id=entity_id',
            '{{table}}.stock_id=1',
            'left')
        ->addStaticField('ref_text')
        ->addExpressionAttributeToSelect(self::$COLUMN_ID_TRADE_REFERENCES,
            'GROUP_CONCAT(ref_text SEPARATOR " ; ")',
            'ref_text')
        ->groupByAttribute('entity_id');
5 Answers

I know it is too late to answer but recently i saw this question so i'm answering as it can help others too.

Reference here: here

You have to create an extension to display category in product grid. Please create following files and it will work for you:

Create a new file on app/code/local/SoftProdigy/AdminGridCategoryFilter/Block/Catalog/Product/Grid/Render/Category.php location and add following code:

<?php
class SoftProdigy_AdminGridCategoryFilter_Block_Catalog_Product_Grid_Render_Category extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
        $product = Mage::getModel('catalog/product')->load($row->getEntityId());
        $cats = $product->getCategoryIds();
        $allCats = '';
        foreach($cats as $key => $cat)
        {
            $_category = Mage::getModel('catalog/category')->load($cat);
            $allCats.= $_category->getName();
            if($key < count($cats)-1)
                $allCats.= ',<br />';
        }
        return $allCats;
    }

}

Create a new file on app/code/local/SoftProdigy/AdminGridCategoryFilter/etc/config.xml location and add following code:

<?xml version="1.0"?>
<config>
    <modules>
        <SoftProdigy_AdminGridCategoryFilter>
            <version>0.0.0.1</version>
        </SoftProdigy_AdminGridCategoryFilter>
    </modules>
    <global>
        <models>
            <admingridcategoryfilter>
                <class>SoftProdigy_AdminGridCategoryFilter_Model</class>
            </admingridcategoryfilter>
        </models>
        <helpers>
            <admingridcategoryfilter>
                <class>SoftProdigy_AdminGridCategoryFilter_Helper</class>
            </admingridcategoryfilter>
        </helpers>
        <blocks>
            <admingridcategoryfilter>
                <class>SoftProdigy_AdminGridCategoryFilter_Block</class>
            </admingridcategoryfilter>
        </blocks>
    </global>
    <adminhtml>
        <events>
            <core_block_abstract_prepare_layout_before>
                <observers>
                    <admingridcategoryfilter>
                        <class>admingridcategoryfilter/observer</class>
                        <method>addCategoryFilterToProductGrid</method>
                    </admingridcategoryfilter>
                </observers>
            </core_block_abstract_prepare_layout_before>
        </events>
    </adminhtml>
</config>

Create a new file on app/code/local/SoftProdigy/AdminGridCategoryFilter/Helper/Data.php location and add following code:

<?php
class SoftProdigy_AdminGridCategoryFilter_Helper_Data extends Mage_Core_Helper_Abstract
{

}

Create a new file on app/code/local/SoftProdigy/AdminGridCategoryFilter/Model/Observer.php location and add following code:

<?php
class SoftProdigy_AdminGridCategoryFilter_Model_Observer
{

    public function addCategoryFilterToProductGrid(Varien_Event_Observer $observer)
    {   
        $block = $observer->getEvent()->getBlock();
        if( ($block instanceof Mage_Adminhtml_Block_Catalog_Product_Grid)  ) {
            $block->addColumnAfter('softprodigy_category_list', array(
                    'header'    => Mage::helper('admingridcategoryfilter')->__('Category'),
                    'index'     => 'softprodigy_category_list',
                    'sortable'  => false,
                    'width' => '250px',
                    'type'  => 'options',
                    'options'   => Mage::getSingleton('admingridcategoryfilter/system_config_source_category')->toOptionArray(),
                    'renderer'  => 'admingridcategoryfilter/catalog_product_grid_render_category',
                    'filter_condition_callback' => array($this, 'filterCallback'),
            ),'name');
        }
    }

    public function filterCallback($collection, $column)
    {
        $value = $column->getFilter()->getValue();
        $_category = Mage::getModel('catalog/category')->load($value);
        $collection->addCategoryFilter($_category);

        return $collection;
    }

}

Create a new file on app/code/local/SoftProdigy/AdminGridCategoryFilter/Model/System/Config/Source/Category.php location and add following code:

<?php
class SoftProdigy_AdminGridCategoryFilter_Model_System_Config_Source_Category
{
    public function toOptionArray($addEmpty = true)
    {
        $options = array();
        foreach ($this->load_tree() as $category) {
            $options[$category['value']] =  $category['label'];
        }

        return $options;
    }



    public function buildCategoriesMultiselectValues(Varien_Data_Tree_Node $node, $values, $level = 0)
    {
        $level++;

        $values[$node->getId()]['value'] =  $node->getId();
        $values[$node->getId()]['label'] = str_repeat("--", $level) . $node->getName();

        foreach ($node->getChildren() as $child)
        {
            $values = $this->buildCategoriesMultiselectValues($child, $values, $level);
        }

        return $values;
    }

    public function load_tree()
    {
        $store = Mage::app()->getFrontController()->getRequest()->getParam('store', 0);
        $parentId = $store ? Mage::app()->getStore($store)->getRootCategoryId() : 1;  // Current store root category

        $tree = Mage::getResourceSingleton('catalog/category_tree')->load();

        $root = $tree->getNodeById($parentId);

        if($root && $root->getId() == 1)
        {
            $root->setName(Mage::helper('catalog')->__('Root'));
        }

        $collection = Mage::getModel('catalog/category')->getCollection()
        ->setStoreId($store)
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('is_active');

        $tree->addCollectionData($collection, true);

        return $this->buildCategoriesMultiselectValues($root, array());
    }
}

Create a new file on app/etc/modules/SoftProdigy_AdminGridCategoryFilter.xml location and add following code:

<?xml version="1.0"?>
<config>
    <modules>
        <SoftProdigy_AdminGridCategoryFilter>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Catalog />
                <Mage_Adminhtml />
            </depends>
        </SoftProdigy_AdminGridCategoryFilter>
    </modules>
</config>

Now clear cache from cache management and you can see category column in product grid.

Related