Magento – Custom Filter Function for Catalog Grid

attributesgridproduct-list

It is possible to change the catalog grid, of the Magento admin-backend.

That is what I have done. I have added custom attributes to the grid like this:

First I added a new Attribute to the collection in the _prepareColection function

    $collection->addAttributeToSelect('ssp_color');

Then I created a new column in the _prepareColumns function

    //prepare $colorValues
    $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'ssp_color');
    $colorValues = array();
    foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
         $colorValues[$option['value']] = $option['label'];
    }

    $this->addColumn('product_color',
        array(
            'header'=> Mage::helper('catalog')->__('Color'),
            'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Colors',
            'index' => 'ssp_color',
            'width' => '100px',
            'type'  => 'options',
            'options' => $colorValues,
    ));

Now everything works fine. I have a dropdown where I can select the attribute-value and it then gets filtered as you can see here:

dropdown

The only problem now is, that some products have multiple values of this attribute but the filter only will return when the value of this attribute is exactly the one I was filtering for.

E.g.: I am filtering for orange and want all products which are avaible in orange but can be avaiable in other colors as well. But the filter now is just returning products which are only avaiable in orange.


The question now is, did someone had this problem before and how did this one got solved. Is it a setting in the _prepareColums function? Or does anybody at least know where the standard filter function is, when there is no filter_condition_callback defined for the column?

Best Answer

The $this->addColumn(...) should get another attribute in the array

$this->addColumn('product_color',
    array(
        'header'=> Mage::helper('catalog')->__('Color'),
        'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Colors',
        'index' => 'ssp_color',
        'width' => '100px',
        'type'  => 'options',
        'options' => $colorValues,
        'filter_condition_callback' => array($this, '_colorFilter'),
));

This will make the function _colorFilter() the filter function for this column.

The function has to be created now:

protected function _colorFilter($collection, $column) {
    if (!$value = $column->getFilter()->getValue()) {
        return $this;
    }
    $field = $column->getFilterIndex() ? $column->getFilterIndex() : $column->getIndex();
    $cond = $column->getFilter()->getCondition();
    $this->getCollection()->addFieldToFilter($field, array('finset' => $cond["eq"]));
    return $this;
}

This will return all products which have at least one appereance of the attribute you filtered for in them, but can contain even more.