Add Category Tree Structure in Magento

public function getCategories()
{
/*$category = Mage::getModel(‘catalog/category’);
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$arr = array();
if ($ids)
{
foreach ($ids as $id)
{
$cat = Mage::getModel(‘catalog/category’);
$cat->load($id);
//$arr[$id] = $cat->getName();
$arr[] = array(‘value’=> $id,’label’=> $cat->getName());
}
}
return $arr;    */
$categories = Mage::getModel(‘catalog/category’)
->getCollection()
->addAttributeToSelect(‘*’)
->addIsActiveFilter();

$all = array();
$prestr=”;
foreach ($categories as $c)
{
//$all[$c] = $c->getName();
$prestr=”;
$level=$c->getLevel();

if($level > 1){
for($i=1;$i< $level;$i++)
{
$prestr.=’- ‘;

}
}

$all[] = array(‘value’=> $c->getId(),’label’=> $prestr.$c->getName());
}

return $all;
}

 

Alternatively,

public function getCategories()
{
$model  =   Mage::getModel(‘catalog/category’);
$rootCategoryId = Mage::app()->getWebsite(true)->getDefaultStore()->getRootCategoryId();
$category = $model->load($rootCategoryId);

$result=array();
$all= Mage::helper(‘brand’)->getCategoriesCustom($category,$rootCategoryId,$result);
return $all;

}

In Data.php File,

public function getCategoriesCustom($parent,$curId,$result){

if($parent->getLevel() == 1){
$result[]=array(‘value’=> $curId,’label’=> $this->getCatNameCustom($parent));
}
else{
$result[]=array(‘value’=> $parent->getId(),’label’=> $this->getCatNameCustom($parent));
}

try{
$children = $parent->getChildrenCategories();

if(count($children) > 0){
foreach($children as $cat){
$result=$this->getCategoriesCustom($cat,$curId,$result);
}
}
}
catch(Exception $e){
return ”;
}
return $result;
}

public function getCatNameCustom($category){
$level = $category->getLevel();
$html = ”;
for($i = 0;$i < $level;$i++){
$html .= ‘-‘;
}
if($level == 1)    return $html.’ ‘.$this->__(“All Categories”);
else return $html.’ ‘.$category->getName();
}

 

 

Advertisements
    • Ananya
    • September 2nd, 2014

    Very Helpful 🙂
    Greatly appreciated.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: