2

I want to sort product collection on category page so that the in stock products shall appear before out of stock products. All the out of stock products will be displayed after the in stock products. I have already rewritten the Mage_Product_Block_List block. After rewriting I have tried the following:

protected function _getProductCollection()
{
    if (is_null($this->_productCollection)) {
        $layer = $this->getLayer();
        /* @var $layer Mage_Catalog_Model_Layer */
        if ($this->getShowRootCategory()) {
            $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
        }

        // if this is a product view page
        if (Mage::registry('product')) {
            // get collection of categories this product is associated with
            $categories = Mage::registry('product')->getCategoryCollection()
                ->setPage(1, 1)
                ->load();
            // if the product is associated with any category
            if ($categories->count()) {
                // show products from this category
                $this->setCategoryId(current($categories->getIterator()));
            }
        }

        $origCategory = null;
        if ($this->getCategoryId()) {
            $category = Mage::getModel('catalog/category')->load($this->getCategoryId());
            if ($category->getId()) {
                $origCategory = $layer->getCurrentCategory();
                $layer->setCurrentCategory($category);
                $this->addModelTags($category);
            }
        }
        **$this->_productCollection = $layer->getProductCollection()->addAttributeToSort('stock_status', desc);**

        $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

        if ($origCategory) {
            $layer->setCurrentCategory($origCategory);
        }
    }

    return $this->_productCollection;
}
  • can you please provide me code?? what you have tried so far – Murtuza Zabuawala Sep 3 '16 at 8:12
  • I have also tried to sort with inventory_stock_availability, is_in_stock, etc. and none worked out for me. – Abhishek Dhanraj Shahdeo Sep 3 '16 at 8:22
  • any update on this?? – Murtuza Zabuawala Sep 5 '16 at 8:05
  • Try My answer and let me know – Murtuza Zabuawala Sep 6 '16 at 16:38
0

you can not do as

$this->_productCollection = $layer->getProductCollection()->addAttributeToSort('stock_status', desc);

To achieve this you have to do left join

$this->_productCollection = $layer->getProductCollection()->joinLeft(array('bs'=>'cataloginventory/stock_status'), 'bs.product_id = e.entity_id', array('stock_status' => 'bs.stock_status'))->order("stock_status desc"); 

try this and let me know its working or not

| improve this answer | |

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.