Magento – Trying to filter by ‘In Stock’ or ‘Out of Stock’ on product admin grid

admincollection;columngridproduct

I have successfully been able to get whether a product is 'In Stock' or 'Out of Stock' in the Magento admin product grid using an observer in the way set out below. However when I try to filter by 'In Stock' or 'Out of Stock' it simply doesn't work.

I believe this is to do with the filter index and ensuring that the collection associates the stock column with the joined table for filtering. I'm unsure how to get this working – if anyone has any suggestions it would be much appreciated. I have set out my existing code below:

etc/config.xml

<config>
<global>
    <models>
        <stockcolumn>
            <class>Creare_Stockcolumn_Model</class>
        </stockcolumn>
    </models>
</global>
<adminhtml>
    <events>
       <eav_collection_abstract_load_before>
            <observers>
                <stockcollection>
                    <class>stockcolumn/observer</class>
                    <method>onEavLoadBefore</method>
                </stockcollection>
            </observers>
        </eav_collection_abstract_load_before>
        <adminhtml_block_html_before>
            <observers>
                <addstockcolumn>
                    <class>stockcolumn/observer</class>
                    <method>onBlockHtmlBefore</method>
                </addstockcolumn>
            </observers>
        </adminhtml_block_html_before>
    </events>
</adminhtml>
</config>

Model/Observer.php

class Creare_Stockcolumn_Model_Observer {

public function onBlockHtmlBefore(Varien_Event_Observer $observer) {
    $block = $observer->getBlock();
    if (!isset($block)) return;

    switch ($block->getType()) {
        case 'adminhtml/catalog_product_grid':
            $block->addColumn('stock_status',
                array(
                       'header'=> 'Stock Status',
                       'width' => '60px',
                       'index' => 'stock_status',
                       'filter_index'=>'inv.stock_status',
                       'type'  => 'options',
                       'options' => array('1'=>'In Stock','0'=>'Out Of Stock'),
                ));
            break;
    }
}

public function onEavLoadBefore(Varien_Event_Observer $observer) {
    $collection = $observer->getCollection();
    $collection->joinTable( array('inv' => 'cataloginventory/stock_item'), 'product_id = entity_id', array("stock_status" => "is_in_stock") )->addAttributeToSelect('stock_status');

}
}

Best Answer

How about adding the stock status to the grid and using that to search with? This link on magento.SE from a few days ago will help you add the Stock Status to the grid and makes for an easy filter tool. I tried it on 1.7.02 and it worked great.