How to Display and Filter Product Categories in Magento Admin Panel

adminhtmlcataloggridproductproduct-list

I am not so much familiar with magento development.i am facing some trouble
my problem is i have add product's associated categories within product name column in admin panel(catalog > manage products) & i have also filter product by categories and i don't have any idea.how to do this task.

Thanks in advance for help

Best Answer

You can rewrite class Mage_Adminhtml_Block_Catalog_Product_Grid in your custom module or put this file into local/Mage/Adminhtml/Block/Catalog/Product.

1) In _prepareColumns method add the following code:

$this->addColumn(
    'category_id',
    array(
        'header'                    => $this->__('Category'),
        'width'                     => '100px',
        'index'                     => 'category_ids',
        'type'                      => 'options',
        'options'                   => $this->getCategoryOptions(),
        'filter_condition_callback' => array($this, '_callbackCategoryFilter'),
        'renderer'                  => '***custom_module***/adminhtml_catalog_product_render_category'
    )
);

2) Create here in class your custom method

public function getCategoryOptions()
{
    $option_array = array();
    $category_collection = Mage::getResourceModel('catalog/category_collection')
        ->addNameToResult()
        ->addAttributeToSort('position', 'asc');
    foreach ($category_collection as $category) {
        if ($category->getId() > 1 && $category->getName() != 'Root Catalog') {
            $option_array[$category->getId()] = $category->getName();
        }
    }
    return $option_array;
}

Or, which is preferable, create this method in your custom helper.

3) Create here in class protected method _callbackCategoryFilter

protected function _callbackCategoryFilter($collection, $column)
{
    if (!$value = $column->getFilter()->getValue()) {
        return null;
    }
    $collection->joinField(
        'category_id',
        'catalog/category_product',
        'category_id',
        'product_id = entity_id',
        '{{table}}.category_id=' . $column->getFilter()->getValue(),
        'inner'
    );
}

4) Create renderer:

class ***Company_Module***_Block_Adminhtml_Catalog_Product_Render_Category
    extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
        $productCategories = array();
        $product = Mage::getModel('catalog/product')->load($row->getData('entity_id'));
        $categories = $product->getCategoryCollection()->addAttributeToSelect('name');
        foreach ($categories as $category) {
            array_push($productCategories, $category->getName());
        }
        return implode('<br>', $productCategories);
    }
}

The result: The result

Related Topic