Magento – How to sort child category collection

categorycollection;magento-1

I a m using this function for getting child categories of current category

    public function getCurrentChildCategories()
    {
        $layer = Mage::getSingleton('catalog/layer');
        $category   = $layer->getCurrentCategory();

        $categories = $category->getChildrenCategories();
        $productCollection = Mage::getResourceModel('catalog/product_collection');
        $layer->prepareProductCollection($productCollection);
        $productCollection->addCountToCategories($categories);
        return $categories;
    }

But i want to sort the collection using category name in ascending order i.e. alphabetically sort i have modified the function like this

    public function getCurrentChildCategories($sort_by = 'name', $sort_order = 'asc')
    {
        $layer = Mage::getSingleton('catalog/layer');
        $category   = $layer->getCurrentCategory();

        $collection = Mage::getModel('catalog/category')->getCollection();

        $collection->addAttributeToSelect('*')
            ->addAttributeToSort('name','asc')
            ->addIdFilter($category->getChildren())
            ->joinUrlRewrite();
            ->load();

        $productCollection = Mage::getResourceModel('catalog/product_collection');
        $layer->prepareProductCollection($productCollection);
        $productCollection->addCountToCategories($collection);
        return $collection;
    }

This should work but this is not working at all..
Any one having any idea about it.

Best Answer

If you remove the extra semi-colon from after joinUrlRewrite then this code will work.

But be aware by calling the function joinUrlRewrite you are limiting your function so it will only work when you are not using flat category catalogue as this function is missing from the class

Mage_Catalog_Model_Resource_Category_Flat_Collection

It does however have the function addUrlRewriteToResult which would appear to give you the same results and when this is called on non flat categories it simply calls joinUrlRewrite so this would be the safer function to us.

Normal Category Collection

Mage_Catalog_Model_Resource_Category_Collection
public function addUrlRewriteToResult()
{
    $this->joinUrlRewrite();
    return $this;
}

Flat Category Collection

Mage_Catalog_Model_Resource_Category_Flat_Collection
public function addUrlRewriteToResult()
{
    $storeId = Mage::app()->getStore()->getId();
    $this->getSelect()->joinLeft(
        array('url_rewrite' => $this->getTable('core/url_rewrite')),
        'url_rewrite.category_id=main_table.entity_id AND url_rewrite.is_system=1 '.
        'AND url_rewrite.product_id IS NULL'.
        ' AND ' . $this->getConnection()->quoteInto('url_rewrite.store_id=?', $storeId).
        ' AND ' . $this->getConnection()->quoteInto('url_rewrite.id_path LIKE ?','category/%'),
        array('request_path')
    );
    return $this;
}
Related Topic