Retrieve categories tree – Magento

Home Magento TopicsRetrieve categories tree – Magento
mage+php

Retrieve categories tree – Magento

No Comments

Retrieve categories tree – Magento .

After use several functions to retrieve the category tree into an array (you can use it in admin form – select or multiselect field), we explain the most optimal solution to do this!

We hope it is useful for you!

 /**
 * Option Category:  Retrieve Category Tree.
 */
 
 
 /** Constants Definition
 const IDENT = '_';
 const IDENT_END = '> ';
 protected $_categories = array();
 
 /**
 *
 * getCategoriesArray: Retrieve Category Tree.
 *
 * @param int $parentId
 * @param int $recursionLevel
 *
 * @return array
*/
 
public function getCategoriesArray($parentId = 1, $recursionLevel = 3)
{
   //Get Level1
   $catlevel1 = 1;
   $Categories = Mage::getModel('catalog/category')
            ->getCollection()
            ->addAttributeToSelect('*')
            ->addIsActiveFilter();
 
   foreach ($Categories as $nodecat) {
      if ($nodecat->getlevel() == 0) {
         $catlevel1 = $nodecat->getEntityId();
      }
   }
 
 
   $recursionLevel = (int)$recursionLevel;
   $parentId = (int)$parentId;
 
   $category = Mage::getModel('catalog/category');
   $storeCategories = Mage::getModel('catalog/category')
            ->getCollection()
            ->addAttributeToSelect('*')
	    ->addFieldToFilter('parent_id',$catlevel1)
	    ->setOrder('position', 'ASC');
 
	    foreach ($storeCategories as $node) {
	       $this->_categories[] = array(
	          'label' => $node->getName(),
		  'value' => $node->getEntityId()
	       );
 
     	       $this->_getChild($node->getEntityId(),2);
 
	    }
 
	    return $this->_categories;
}	
 
 
/**
*
* _getChild: Retrieve sub-levels
*
* @param int $catid - Id Category
* @param int $level - Tree Level
*/
 
protected function _getChild($catid,$level)
{
   $storeCategories = Mage::getModel('catalog/category')
                    ->getCollection()
                    ->addAttributeToSelect('*')
		    ->addFieldToFilter('parent_id',$catid)
		    ->setOrder('position', 'ASC');
 
   foreach ($storeCategories as $node) {
      $prefix = str_repeat(self::IDENT, $level * 1 -1) . self::IDENT_END;
 
      $this->_categories[] = array(
         'label' => $prefix . $node->getName(),
	 'value' => $node->getEntityId()
      );
 
      $this->_getChild($node->getEntityId(),$level+1);
 
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *