add category tree structure in magento

this post we will see how generate a category tree, recursively showing all categories and sub categories.

Preparing function in  magento

public function getCategoriesArray() {
    $categoriesArray = Mage::getModel('catalog/category')
            ->addAttributeToSort('path', 'asc')
    $categories = array();
    foreach ($categoriesArray as $categoryId => $category) {
        if (isset($category['name']) && isset($category['level'])) {
            $categories[] = array(
                'label' => $category['name'],
                'level'  =>$category['level'],
                'value' => $categoryId
    return $categories;

Front end  form please add below code to display your category

$fieldset->addField('categories', 'multiselect', array(
            'label' => $this->__('Categories'),
            'name' => 'categories',
            'values' => $this->getCategoriesArray(),

Related posts