Saturday, December 20, 2014

Magento Flat category , show category tree

Below code displays dropdown of categories and subcategories upto n level.


<!----NEW CODE---->

<select id="category-changer"  name="cat" style="width:150px;">
<option value="6"> All Categories </option>
<?php echo $catlistHtml; ?>  
</select>
<?php
function str_prefix($str, $n=1, $char=" "){
    for ($x=0;$x<$n;$x++){ $str = $char . $str; }
    return $str;
}
function getTreeCategories($parentId, $isChild){
    $_cathelper = Mage::helper('catalog/category');
$allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active','1')
                ->addAttributeToFilter('parent_id',array('eq' => $parentId));
    $class = ($isChild) ? "sub-cat-list" : "cat-list";
    //$children = Mage::getModel('catalog/category')->getCategories(7);
    foreach ($allCats as $category)
    {
   $prefix = '';
   $_category =  Mage::getModel('catalog/category')->load($category->getId());
   $lblval=$_category->getLevel()-3;
$catname = ($lblval==0)?strtoupper($_category->getName()):$_category->getName();
$catname =  str_prefix($catname,$lblval*2,"-");
        $html .= '<option lbl="'.$_category->getLevel().'" value="'.$_category->getId().'" caturl="'.$_cathelper->getCategoryUrl($_category).'" >'.$catname."</option>";
        $subcats = $category->getChildren();
        if($subcats != ''){
            $html .= getTreeCategories($category->getId(), true);
        }
    }
    return $html;
}
$catlistHtml = getTreeCategories(6, false);
?>

<!--NEW CODE ENDS-->