A
A
Anton2014-10-19 20:44:00
Yii
Anton, 2014-10-19 20:44:00

How to make a tree view in Yii2?

Hello!
There is a DB with categories. There are both main categories and subcategories.
Example :
- Movies (id=1, parent_id=0)
------ Science Fiction (id=3, parent_id=1)
------ Horror (id=4, parent_id=1)
- Series (id= 2, parent_id=0)
It turned out to display a list of categories of this kind:
- Movies (id=1, parent_id=0)
- Series (id=2, parent_id=0)
- Science Fiction (id=3, parent_id=1)
- Horror (id =4, parent_id=1)
And you need to make sure that the subcategories are under the main categories.
Sorting by id and without nesting.
I hope that I clearly painted the essence of what is needed. Thank you in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LAV45, 2014-10-20
@LAV45

class Menu extends ActiveRecord
{
// ...
    public static function getList()
    {
        $data = static::find()
            ->select(['id', 'parent_id', 'title'])
            ->orderBy('parent_id ASC')
            ->asArray()
            ->all();

        $sort = new SortList([
                'data' => $data,
                'prefix' => '------',
        ]);
        $sortList = ArrayHelper::map($sort->getList(), 'id', 'title');
        return $sortList;
    }
}

class SortList extends Object
{
    public $data;

    public $prefix = '   ';

    protected function getPath($category_id, $prefix = false)
    {
        foreach ($this->data as $item) {
            if ($category_id == $item['id']) {
                $prefix = $prefix ? $this->prefix . $prefix : $item['title'];
                if ($item['parent_id']) {
                    return $this->getPath($item['parent_id'], $prefix);
                } else {
                    return $prefix;
                }
            }
        }
        return '';
    }

    public function getList($parent_id = 0)
    {
        $data = [];

        foreach ($this->data as $item) {
            if ($parent_id == $item['parent_id']) {
                $data[] = [
                    'id' => $item['id'],
                    'title' => $this->getPath($item['id'])
                ];
                $data = array_merge($data, $this->getList($item['id']));
            }
        }

        return $data;
    }
}

S
SOb_S, 2014-11-11
@SOb_S

I liked this solution: https://github.com/creocoder/yii2-nested-set-behavior Implemented branch modification, insertion, deletion, change of roots, multiple roots, etc..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question