4

I am trying to add a column to a module that will shows products and the related category. I have been able to show the product names etc put I am not able to get the category name to show in the grid.

Grid.php

<?php

class Custom_Module_Block_Adminhtml_Export_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    public function __construct()
    {
        parent::__construct();
        $this->setId('productGrid');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->setVarNameFilter('product_filter');

    }

    protected function _getStore()
    {
        $storeId = (int) $this->getRequest()->getParam('store', 0);
        return Mage::app()->getStore($storeId);
    }

    protected function _prepareCollection()
    {
        $store = $this->_getStore();
        $collection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('category_ids')
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('attribute_set_id')
            ->addAttributeToSelect('type_id');

        if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
            $collection->joinField('qty',
                'cataloginventory/stock_item',
                'qty',
                'product_id=entity_id',
                '{{table}}.stock_id=1',
                'left');
        }
        if ($store->getId()) {
            //$collection->setStoreId($store->getId());
            $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
            $collection->addStoreFilter($store);
            $collection->joinAttribute(
                'name',
                'catalog_product/name',
                'entity_id',
                null,
                'inner',
                $adminStore
            );
            $collection->joinAttribute(
                'custom_name',
                'catalog_product/name',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute(
                'status',
                'catalog_product/status',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute(
                'visibility',
                'catalog_product/visibility',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute(
                'price',
                'catalog_product/price',
                'entity_id',
                null,
                'left',
                $store->getId()
            );
        }
        else {
            $collection->addAttributeToSelect('price');
            $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
            $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
        }


        $this->setCollection($collection);
        parent::_prepareCollection();
        $this->getCollection()->addWebsiteNamesToResult();
        return $this;
    }

    protected function _addColumnFilterToCollection($column)
    {
        if ($this->getCollection()) {
            if ($column->getId() == 'websites') {
                $this->getCollection()->joinField('websites',
                    'catalog/product_website',
                    'website_id',
                    'product_id=entity_id',
                    null,
                    'left');
            }
        }
        return parent::_addColumnFilterToCollection($column);
    }

    protected function _prepareColumns()
    {


        $this->addColumn('entity_id',
            array(
                'header'=> Mage::helper('catalog')->__('ID'),
                'width' => '50px',
                'type'  => 'number',
                'index' => 'entity_id',
            ));
        $this->addColumn('name',
            array(
                'header'=> Mage::helper('catalog')->__('Name'),
                'index' => 'name',
            ));

        $store = $this->_getStore();
        if ($store->getId()) {
            $this->addColumn('custom_name',
                array(
                    'header'=> Mage::helper('catalog')->__('Name in %s', $store->getName()),
                    'index' => 'custom_name',
                ));
        }

        $this->addColumn( 'categories',
            array(
                'header' => Mage::helper( 'catalog' )->__( 'Categories' ),
                'width' => '100px',
                'sortable' => true,
                'index' => 'categories',
                'sort_index' => 'category',
                'filter_index' => 'category'
            ));

        $this->addColumn('type',
            array(
                'header'=> Mage::helper('catalog')->__('Type'),
                'width' => '60px',
                'index' => 'type_id',
                'type'  => 'options',
                'options' => Mage::getSingleton('catalog/product_type')->getOptionArray(),
            ));

        $sets = Mage::getResourceModel('eav/entity_attribute_set_collection')
            ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId())
            ->load()
            ->toOptionHash();

        $this->addColumn('set_name',
            array(
                'header'=> Mage::helper('catalog')->__('Attrib. Set Name'),
                'width' => '100px',
                'index' => 'attribute_set_id',
                'type'  => 'options',
                'options' => $sets,
            ));

        $this->addColumn('sku',
            array(
                'header'=> Mage::helper('catalog')->__('SKU'),
                'width' => '80px',
                'index' => 'sku',
            ));

        $store = $this->_getStore();
        $this->addColumn('price',
            array(
                'header'=> Mage::helper('catalog')->__('Price'),
                'type'  => 'price',
                'currency_code' => $store->getBaseCurrency()->getCode(),
                'index' => 'price',
            ));

        if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
            $this->addColumn('qty',
                array(
                    'header'=> Mage::helper('catalog')->__('Qty'),
                    'width' => '100px',
                    'type'  => 'number',
                    'index' => 'qty',
                ));
        }

        $this->addColumn('visibility',
            array(
                'header'=> Mage::helper('catalog')->__('Visibility'),
                'width' => '70px',
                'index' => 'visibility',
                'type'  => 'options',
                'options' => Mage::getModel('catalog/product_visibility')->getOptionArray(),
            ));

        $this->addColumn('status',
            array(
                'header'=> Mage::helper('catalog')->__('Status'),
                'width' => '70px',
                'index' => 'status',
                'type'  => 'options',
                'options' => Mage::getSingleton('catalog/product_status')->getOptionArray(),
            ));

        if (!Mage::app()->isSingleStoreMode()) {
            $this->addColumn('websites',
                array(
                    'header'=> Mage::helper('catalog')->__('Websites'),
                    'width' => '100px',
                    'sortable'  => false,
                    'index'     => 'websites',
                    'type'      => 'options',
                    'options'   => Mage::getModel('core/website')->getCollection()->toOptionHash(),
                ));
        }

        if (Mage::helper('catalog')->isModuleEnabled('Mage_Rss')) {
            $this->addRssList('rss/catalog/notifystock', Mage::helper('catalog')->__('Notify Low Stock RSS'));
        }

        $this->addExportType('*/*/exportCsv', Mage::helper('sales')->__('CSV'));
        $this->addExportType('*/*/exportExcel', Mage::helper('sales')->__('Excel'));

        return parent::_prepareColumns();
    }

    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current'=>true));
    }
} 

I'm not quite sure if I need to add a Table Join or Join Attribute and would welcome any assistance please!

9

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.

  • I have implemented your code and I can see the categories but they are showing in every column!! – user1704524 Jan 8 '14 at 17:12
  • With the above code a separate category column will be display. – SoftProdigy Jan 9 '14 at 5:48
  • I had already created a module which diplayed the products in a Grid but I needed the categories so added your code but I was getting the categories in all my columns... – user1704524 Jan 9 '14 at 15:26
  • It is correct to have the module created under the local code branch as its a local customisation - community is is for extensions which will be made publicly available. As such the class files should be created under app/code/local/ as opposed to changing the codePool to community. – Jonathan Hussey Nov 6 '14 at 10:57
  • Very good ! works fine for me. – PMB Mar 28 '16 at 11:26
1

Minor update,

in the: app/code/local/SoftProdigy/AdminGridCategoryFilter/etc/config.xml

needs to actually be:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<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>
</default>
</setup>
0

I've done all the steps according to SoftProdigy answer, but nothing happend.

Should I add something in grid.php or call any function to make it works?

A while after this post i found the problem: in app/etc/modules/SoftProdigy_AdminGridCategoryFilter.xml

shoud be <codePool>community</codePool>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.