Visualization tree-multi subcategories as listbox or dropdownlist

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

Do you want to make a listbox or dropdownlist to select one or more categories or sub categories ?

I am sure you have seen that in cms like drupal-wordpress-joomla etc on administrator panel

For example when you create an article you have to select the (sub)categories that it will be appeared, or if you want to make a relation between two or more subcategories you have to do something similar

So, Let's do it in Yii!

We will need the code that generates the tree according to database schema, so check this generate multilever sub categories first

in the same controller (or component) create these methods

public static function getListTreeView() {
        if (empty(self::$catTree)) {
            self::getCategoryTree();
        }
        return self::visualTree(self::$catTree, 0);
 }

    private static function visualTree($catTree, $level) {
        $res = array();
        foreach ($catTree as $item) {
            $res[$item['id']] = '' . str_pad('', $level * 2, '-') . ' ' . $item['label'];
            if (isset($item['items'])) {
                $res_iter = self::visualTree($item['items'], $level + 1);
                foreach ($res_iter as $key => $val) {
                    $res[$key] = $val;
                }
            }
        }
        return $res;
    }

now in your views (_form.php) insert this code

1) about select one category by dropdown list (associating categories)

echo $form->labelEx($category,'parent_id');
echo $form->dropDownList($category, 'parent_id', self::getListTreeView(), array('prompt' => 'a prompt')); 
echo $form->error($category,'parent_id');

2) about Select multi categories by listbox (for example an article has many categories)

$selected = array();

foreach ($article->Categories as $item) {
    $selected[$item->category_id]=array('selected' => 'selected');
}

$data = self::getListTreeView(); 
$htmlOptions = array('multiple' => 'true', 'options' => $selected);

echo $form->labelEx($model, 'listCategories');
echo $form->error($model, 'listCategories'); 
echo $form->listBox($model, 'listCategories', $data, $htmlOptions);

Note: article is an implemented model that has been associated with categories

The class of article must contains a relation like that

public function relations()
{
	return array(
		 ...
'Categories' => array(self::MANY_MANY, 'Category', 'article_category(category_id, article_id)'),
	);
}

Thats it!