G
G
Greg Popov2016-06-14 22:41:18
Yii
Greg Popov, 2016-06-14 22:41:18

What is the error when building nested sets menu Yii2?

Hello. I am building a regular menu implemented on nested sets:

/**
     * @param Category[] $categories
     * @param int $activeId
     * @param int $parent
     * @return array
     */
    private function getMenuItems($categories, $activeId = null, $parent = null)
    {
        $list = [];
        foreach ($categories as $category) {
            if($category->lft >= $category->id && $category->rgt >= $category->id){
                $list[$category->id] = [
                    'active' => $activeId === $category->id,
                    'label' => $category->name,
                    'url' => ['catalog/list', 'id' => $category->id],
                    'items' => $category->children()->all()
                ];
            }else{
                $list[$category->id] = [
                    'active' => $activeId === $category->id,
                    'label' => $category->name,
                    'url' => ['catalog/list', 'id' => $category->id],
                ];
            }
        }
        return $list;
    }

If you recursively build, it gives an error 500, if so, it does not see children, what is the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Greg Popov, 2016-06-15
@Gregpopov

public static function getTree($categories, $left = 0, $right = null, $lvl = 1){

        $tree = [];

        foreach ($categories as $index => $category) {
            if ($category->lft >= $left + 1 && (is_null($right) || $category->rgt <= $right) && $category->lvl == $lvl) {
                $tree[$index] = [
                    'id' => $category->id,
                    'label' => $category->name,
                    'url' => ['/shop/catalog/list', 'id' => $category->id],
                    'items' => self::getTree($categories, $category->lft, $category->rgt, $category->lvl + 1),
                ];
            }
        }

        return $tree;

    }
    
    public static function getFullTreeStructure(){

        $roots = Category::find()->roots()->addOrderBy('root, lft')->all();
        $tree = [];
        foreach ($roots as $root){
            $tree [] = [
                'id' => $root->id,
                'label' => $root->name,
                'url' => ['/shop/catalog/list', 'id' => $root->id],
                'items' => self::getTree($root->children()->all()),
            ];
        }

        return $tree;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question