Magento Get Category List As Admin Select

back to tech articles
Magento CE 1.8.0.0

Sometimes we want to retrieve a list of all categories on site to populate a select input field in admin. Here’s one way this can be achieved.

I’m assuming we have a custom module called My_Module in the community folder.

File: app/code/community/My/Module/Helper/Data.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
...
public function getAllCategoriesArray($optionList = false)
{
    $categoriesArray = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('url_path')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))
        ->load()
        ->toArray();

    if (!$optionList) {
        return $categoriesArray;
    }

    foreach ($categoriesArray as $categoryId => $category) {
        if (isset($category['name'])) {
            $categories[] = array(
                'value' => $category['url_path'],
                'label' => Mage::helper('my_module')->__($category['name'])
            );
        }
    }

    return $categories;
}
...

Now that we have our public function available from the helper, we can use this to get a list of the categories, or just return an array of the values.

For this article, we’re creating a select input field in an admin form, so have the following usage.

File: app/code/community/My/Module/Block/Adminhtml/Module/Edit/Tab/Main.php

1
2
3
4
5
6
7
8
9
10
11
12
protected function _prepareForm()
{
...
$fieldset->addField('categories', 'select', array(
    'name' => 'categories',
    'label' => Mage::helper('my_module')->__('Categories'),
    'title' => Mage::helper('my_module')->__('Categories'),
    'required' => false,
    'values' => Mage::helper('my_module')->getAllCategoriesArray(true)
));
...
}

Obviously there’s more to these files than I’ve shown, this is just to illustrate the use of the function.

Hope that helps someone!

Leave a Reply

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