mahsa.teimourikia
mahsa.teimourikia

Reputation: 1774

Yii showing treeview in dropdownlist from database

I have categories and subcategories saved in a database. I want to show them in a CHtml dropdown like this:

Patrent_cat
   sub_cat1
   sub_cat2
Parent_cat2
  ...

My category table is like this

id name parent_id

and parent_id is 0 if the tuple is a parent itself

I already tried this in my Category model:

public function relations()
{
    return array(
                'getparent' => array(self::BELONGS_TO, 'Category', 'parent_id'),
                'childs' => array(self::HAS_MANY, 'Category', 'parent_id', 'order' => 'id ASC'),
    );
}

public function getCategoryTree() 
    {
        $subitems = array();
        if($this->childs) foreach($this->childs as $child) 
        {
            $subitems[] = $child->getListed();
        }
        $returnarray = array($this->id => $this->title);
        if($subitems != array()) 
            $returnarray = array_merge($returnarray, array('items' => $subitems));
        return $returnarray;
    }

and in my view:

<?php 
         echo CHtml::dropDownList('category', 'id', 
                        Category::model()->CategoryTree,
                        array('empty' => '(Select a category'));
?>

but it gives me a empty dropdown. How can I show this treeview in the dropdownlist with option groups? (The option groups are the parent categories and the options are sub_categories.

Upvotes: 3

Views: 4078

Answers (3)

den
den

Reputation: 1

public function getDropdownCategories()
    {
        $array = self::find()->select(['id', 'parent_id', 'name'])->asArray()->all();
        $array = self::buildTree($array);
        $array = ArrayHelper::map($array, 'id', 'name');
        return $array;
    }

private function buildTree($array, $parentId = null, $preWord = '')
    {
        if(!empty($preWord))
            $preWord.='-';

        $tmpArray = [];
        foreach ($array as $element) {
            if ($element['parent_id'] == $parentId) {
                $tmpArray[] = ['id' => $element['id'], 'name' => $preWord.$element['name']];
                $tmp = self::buildTree($array, $element['id'], '-');
                if(!empty($tmp) && is_array($tmp)) {
                    foreach ($tmp as $item) {
                        $tmpArray[] = ['id' => $item['id'], 'name' => $item['name']];
                    }
                }
            }
        }
        return $tmpArray;
    }

Upvotes: 0

driver_by
driver_by

Reputation: 1695

You create empty model and try to get it's childs Category::model()->CategoryTree so you have got empty result.

Try method to get the list of child categories in your model:

public function getChildList() {
    $return = array();
    if ($this->childs !== null) {
        foreach ($this->childs as $child) {
            $return[$child->id] = "--".$child->title;
        }
    }
    return $return;
}

On your controller action:

...
$categotyList = array();
$parentCategories = Category::model()->findAllByAttributes(array('parent_id'=>'0'));
foreach ($parentCategories as $category) {
    array_merge($categoryList, 
               array('$category->id' => '$category->name'), 
               $category->getChildList()
    );
}
...

And view:

echo CHtml::dropDownList('category', 'id', 
                        $categoryList,
                        array('empty' => '(Select a category'));

Check the code for errors, and modify as you needed.

Upvotes: 0

WebDevPT
WebDevPT

Reputation: 588

Try this

echo $form->dropDownList($model,'id',CHtml::listData(SubCat::model()->findAll(),'id', 'name','relation_name.name'),array('prompt'=>'Choose'));

this will show parents and sub-categories on the dropdown

Upvotes: 7

Related Questions