我在数据库中保存了类别和子类别。我想在这样的CHtml下拉列表中显示它们:
Patrent_cat
sub_cat1
sub_cat2
Parent_cat2
...
我的类别表就像这样
id name parent_id
如果元组是父元素,则parent_id为0
我已经在我的分类模型中试过了这个:
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;
}
在我看来:
<?php
echo CHtml::dropDownList('category', 'id',
Category::model()->CategoryTree,
array('empty' => '(Select a category'));
?>
但它给了我一个空的下拉列表。如何在带有选项组的下拉列表中显示此树视图? (选项组是父类别,选项是sub_categories。
答案 0 :(得分:7)
试试这个
echo $form->dropDownList($model,'id',CHtml::listData(SubCat::model()->findAll(),'id', 'name','relation_name.name'),array('prompt'=>'Choose'));
这将在下拉列表中显示父母和子类别
答案 1 :(得分:0)
您创建空模型并尝试获取它的子项Category::model()->CategoryTree
,因此您的结果为空。
尝试获取模型中子类别列表的方法:
public function getChildList() {
$return = array();
if ($this->childs !== null) {
foreach ($this->childs as $child) {
$return[$child->id] = "--".$child->title;
}
}
return $return;
}
在您的控制器操作上:
...
$categotyList = array();
$parentCategories = Category::model()->findAllByAttributes(array('parent_id'=>'0'));
foreach ($parentCategories as $category) {
array_merge($categoryList,
array('$category->id' => '$category->name'),
$category->getChildList()
);
}
...
并查看:
echo CHtml::dropDownList('category', 'id',
$categoryList,
array('empty' => '(Select a category'));
检查代码是否有错误,并根据需要进行修改。
答案 2 :(得分:0)
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;
}