Enhanced Catalog Product Grid – Custom Attribute Filter

Featured Image

Sometimes one needs to have additional filtering criteria inside of a catalog’s product grid. Here is an extension that adds custom product attribute to search filter. You can choose to use any product attribute and it will be shown in the product grid.

The extension settings shows up under System->Configuration menu in its separate tab.

I decided to ignore some attributes, so not all are shown. Ignored are attributes:

  • which are already selected by the product grid (‘sku’, ‘name’, ‘qty’, ‘price’, ‘status’, ‘visibility’)
  • that have no products assigned to them

The “Attribute to filter by” combo box is declared in extensions system.xml file as:

<filter_attribute>
   <label>Attribute to filter by</label>
   <frontend_type>select</frontend_type>
   <source_model>inchoo_product_filter/attributes</source_model>
   <sort_order>2</sort_order>
   <show_in_default>1</show_in_default>
   <show_in_website>0</show_in_website>
   <show_in_store>0</show_in_store>
 </filter_attribute>

The model with the reference “inchoo_product_filter/attributes” is shown here:

<?php
class Inchoo_Productfilter_Model_Attributes
{
    public function toOptionArray()
    {
    	$ignoreAttributes = array('sku', 'name', 'attribute_set_id', 'type_id', 'qty', 'price', 'status', 'visibility');
    	$collection = Mage::getResourceModel('catalog/product_attribute_collection')
            ->addVisibleFilter();
        $result = array();
    	foreach ($collection as $model) {
    		if(in_array($model->getAttributeCode(), $ignoreAttributes)) {
    			continue;
    		}
    		$productCollection = Mage::getModel('catalog/product')->getCollection();
    		$productCollection->addAttributeToSelect(array($model->getAttributeCode()));
    		$productCollection->addAttributeToFilter($model->getAttributeCode(), array('gt' => 0));
    		if(count($productCollection->getData()) > 0) {
    			$result[] = array('value' => $model->getAttributeCode(), 'label'=>$model->getFrontendLabel());
    		}
        }
       return $result;
    }
}

The chosen product attribute is shown in the product grid:

To add another column to the grid we need to override the Magento’s class: Mage_Adminhtml_Block_Catalog_Product_Grid.

First the _prepareCollection() function:

 protected function _prepareCollection()
    {
    	if(Mage::getStoreConfig(self::CONFIG_ENABLED)) {
    		//removed parent's code for clarity
    		//this extension specific
    		$attributeCode = Mage::getStoreConfig(self::CONFIG_ATTRIBUTE_CODE);
    		$collection->joinAttribute($attributeCode, 'catalog_product/'.$attributeCode, 'entity_id', null, 'left');
    		$collection->addAttributeToSelect($attributeCode);
    		$this->setCollection($collection);
    		Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();
    		$this->getCollection()->addWebsiteNamesToResult();
    		//this extension specific end
    	} else {
    		parent::_prepareCollection();
    	}
    	return $this;
    }

Then we add custom column by averriding _prepareColumns() function:

protected function _prepareColumns()
    {
    	if(Mage::getStoreConfig(self::CONFIG_ENABLED)) {
    		// removed parent's code for other columns for clarity
    		// this extension specific
    		$attributeCodeConfig = Mage::getStoreConfig(self::CONFIG_ATTRIBUTE_CODE);
    		$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product', $attributeCodeConfig);
    		$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
    		$attributeData = $attribute->getData();
    		$frontEndLabel = $attributeData['frontend_label'];
    		$attributeOptions = $attribute->getSource()->getAllOptions();
    		$b = new Mage_Catalog_Model_Resource_Eav_Attribute();
    		$attributeOptions2 = array();
    		foreach ($attributeOptions as $value) {
    			if(!empty($value['value'])) {
    				$attributeOptions2[$value['value']] = $value['label'];
    			}
    		}
    		if(count($attributeOptions2) > 0) {
    			$this->addColumn($attributeCodeConfig,
    				array(
                		'header'=> Mage::helper('catalog')->__($frontEndLabel),
                		'width' => '80px',
                		'index' => $attributeCodeConfig,
                		'type'  => 'options',
                		'options' => $attributeOptions2,
    			));
    		} else {
    			$this->addColumn($attributeCodeConfig,
    				array(
                		'header'=> Mage::helper('catalog')->__($frontEndLabel),
                		'width' => '80px',
                		'index' => $attributeCodeConfig,
    			));
    		}
    	// this extension specific end
	// removed parent's code for other columns for clarity
        $this->addRssList('rss/catalog/notifystock', Mage::helper('catalog')->__('Notify Low Stock RSS'));
        Mage_Adminhtml_Block_Widget_Grid::_prepareColumns();
    	} else {
    		parent::_prepareColumns();
    	}
        return $this;
    }

This is definitely not all the code used in this extension. You can download the newest version of the extension here.

45
Top

Care to rate this post?

Author

Milovan Gal

Ex. Inchooer

Milovan was working at Inchoo for one year from June 2011 to March 2013 as a backend developer.

Other posts from this author

Discussion 45 Comments

Add Comment
  1. Welcome to the club :)

  2. D Hassen

    I couldn’t get this working on EE 1.8. I just get a blank screen when I go to the Product Filter config page, even after refreshing the cache and logging back in.

  3. Congratulations on the 1st post Milovan. Keep them coming. :)

    Cheers from Ljubljana.

  4. Ivica

    Congrats, Gal.

    Good one.

  5. Nicola

    Worked perfectly!
    Thanks again!

  6. Milovan Gal

    @D Hassen,

    I just tested it on EE 1.8 and it works for me.

    Do you have any other extension which affects the product grid?

  7. D Hassen

    @Milovan

    Yes, totally a rookie mistake. It works great. Thank you for sharing this, it is Very helpful.

  8. IdeI

    Great work, but…

    I have a problem… when I use the grid filter, in the custom columb is empty why?

    Perfect work all products

  9. Milovan Gal

    @IdeI
    I am not sure I understood you well. If I didn’t, please, rephrase your question!
    For attributes that don’t have options, the custom column header is a text field, so you need to enter the text you want to search for.

  10. IdeI

    Product grid with custom column

    View all products the custom column is great
    name custom
    aaa xxx
    bbb yyyy

    View filtered products (example: name = aaa) the custom column is empty
    name custom
    aaa empty

  11. Andy

    Hi, I’ve got this installed and it works ok, but when active, it prevents the sku from showing/being searchable.

    It’s not a huge problem as I just enable the module when I need to filter, but any ideas what might be causing this? We’re on 1.5.1 and don’t have any other extensions installed that affect the product grid.

    Thanks

  12. Milovan Gal

    @Andy

    Thank you very much for your post and for finding a bug!
    I have just fixed the issue with not showing the sku and updated the download link to a new version of the extension.

    Thanks again!
    Cheers

  13. Andy

    @Milovan

    That’s great Milovan, nice to see it’s not me breaking it for once!

    Downloading now.

    Thanks again

  14. Benoît

    Hi,

    For the people interested in this feature, I just released a new version of my free extension that allows to do this for any number of attributes (and for the customers as well), and much much more

    You can get it on the Magento Connect here : http://www.magentocommerce.com/magento-connect/bleulliette/extension/7619/bl_customgrid

  15. Absolutely HUGE! I’ve spend DAYS on past products trying to incorporate this feature. THANKS INCHOO!

  16. Hello,

    After I copied the extension to Magento and refreshed cache the Inchoo section showed in configuration, but trying to enter it results in “404 error”.

    Is there anything else that should be done except copying?

    Thx in advance,
    Adrian

  17. Ivica

    @Adrian,

    Did you try to log out, and then log back into admin?
    This usually needs to be done after extension installation to update Magento Admin permissions.

    Cheers

  18. Hi,
    How to add “Stock Availability”?
    Thanks

  19. Stefan

    Great Module.

    Best regards,
    Stefan

  20. Sam

    Anyone know an extension that will let me do this for the front end? (i.e. customers filtering by custom attributes)

  21. shyam

    It’s installed and works, but it only finds a few of my custom attributes, and not others? I’m confused by what it’s looking for. I want the attribute called “photographer” in this, however, the dropdown only shows weight, tax class and is product available on google checkout. What am I missing?

  22. Milovan Gal

    Hi shyam,
    Did you set the photographer attribute on any product?

  23. Hello,

    Thanks for your post!

    Nevertheless, i have a problem. After using the “Name” filter, the custom attribute values disappear…
    Weird thing is this is only happening with the “Name” column.
    When debugging, values are like decimals. Hence, the labels not showing up.
    Do you have any clue ?

    Thanks in advance

  24. Guicara

    Hi,

    Thanks for your extension. Unfortunately it doesn’t work with Magento 1.6. I have two problems:

    1) The “$attributeOptions = $attribute->getSource()->getAllOptions(true);” return an empty array.

    2) My custom column attribute is empty when I load the “catalog_product/index/” page. But the filter function works well.

    Any idea?
    Thanks!

  25. Manpreet Singh

    I have installed this extension in Magento 1.7 version it is showing in System > Configuration but when i open it 404 Error
    Page not found.
    is coming.

    Can anyone help me.
    Thanks in Advance

  26. Milovan Gal

    @ Manpreet,

    Did you log out and log in back to Admin? This is a standard procedure when installing any Magento extension.

  27. Caroline

    Hi,

    How can I make this compatible with Mass Product Actions from Amasty. Anyone? It’s seems so cool to select product by attribute and than assign them in bulk to a category. But this code removes the other extension..

  28. nilesh

    Fatal error: Class ‘Inchoo_Productfilter_Helper_Data’ not found in C:\xampp\htdocs\AthleticPlanet\app\Mage.php on line 546

    i am getting above error while trying to open admin panel

  29. Milovan Gal

    Hi nilesh,
    You probably didn’t unpack the extension in the right place. Please, unpack it in the root of your Magento installation. Then delete var/cache directory to be sure.

    If this doesn’t solve your problem, please tell me which version of Magento you are using.

  30. alex

    hey.
    Them module works great. I would like to sort the products if the have images or not. Any ideas?

  31. Michal Moc

    Nice post but i have one question about “how add CUSTOM filter” to grid.

    for example, i have grid with product, add column with selected and group category.

    Product is in category ID 3,7,11…

    How can i filter “in” (how filter only product in category 7…)?

    My code is:

    protected function _prepareCollection()
    {
    /* @var $collection Mage_Catalog_Model_Resource_Product_Collection */
    $collection = Mage::getModel(‘catalog/product’)->getCollection();
    $collection->addAttributeToSelect(‘*’);
    $collection->joinField(‘category_id’, ‘catalog/category_product’, ‘category_id’, ‘product_id=entity_id’, null, ‘left’);
    $collection->groupByAttribute(‘entity_id’);
    $collection->addStaticField(‘category_id’);
    $collection->addExpressionAttributeToSelect(‘category_grp’, ‘GROUP_CONCAT(category_id)’, ‘category_id’);

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

    protected function _prepareColumns()
    {
    parent::_prepareColumns();

    $this->addColumn(‘category_id’, array(
    ‘header’ => Mage::helper(‘newsletter’)->__(‘Category’),
    ‘index’ => ‘category_grp’,
    ‘type’ => ‘categories’,
    ‘options’ => $options,
    ‘align’ => ‘left’,
    // ‘filter_index’ => $this->_getFlatExpressionColumn(‘category’),
    return $this;
    }

  32. Very nice extension. I have used it & also modified to display multiple attribute in product grid.

    Thanks for sharing such extension

  33. Siby

    how can i filter attribute with category. i mean, i want size attribute used in a specific category.
    For example if shoe is the category i want to list size of all products used in the shoe category.
    plz help me

  34. Mattue

    If somebody is looking for good navigation extension for your online shop, i strongly recommended amasty’s one.

    If you have some questions you can write to this guys and they will help you.

    Best,
    Matt

  35. amey

    pls tel me how to include multiple attributes

  36. Hello Amey,

    I have modified above module and enhance functionality for multiselect attribute filter.
    Few more things like category filter, product image also included in grid.

    You can check the code in below github link:
    https://github.com/bijalbhavsar/Magecracker_Advancefilter

  37. billy

    hello everybody
    if you are interested in interesting and useful extension i can recommend you one.

    i use it for a long time and pleased with it.

    http://amasty.com/extended-product-grid.html

  38. Roy

    I wanted qty as a filter for product listing in front end.. meaning in list page i wanted to give user the feature to filter down for products that have x qty or a range of qty.. is this possible?

  39. Another great tutorial that really works from inchoo

    I always come here first …

    Thanks

    Wayne

  40. Danny

    thanks,works great, but how can I use it in related product section ?
    right now it only shows in product management page,I want this to work in related product section when editing a product.

  41. Dixon Tran

    after being installed, I add attribute but it not show. what do i need to config more ?

  42. I’m getting:
    Fatal error: Class ‘Inchoo_Productfilter_Helper_Data’ not found in /var/www/vhosts/bato/public_html/app/Mage.php on line 545

    URL to extantion is: /app/code/local/Inchoo/Productfilter/

    Please help me :(

  43. Shon

    This extension is great, however, I need to filter by unit price range just like the price column has ‘from’ and ‘to’ range, I added the unit price column just fine but how can I filter by unit price range?

  44. Jatinder

    This extension does not display all filter attributes, I meant, I have added 3 custom attributes for product only one of them is shown in the dropdown option, :(

  45. theobaldus

    How can I add manufacturer column with filter in Admin?

Add Your Comment

Please wrap all source codes with [code][/code] tags.
Top