NullRefExcep/yii2-category

getParents issue

satoved opened this issue · 6 comments

Hello, I've found a bug in models/Category.php getParents()

The code

    public function getParents()
    {
        $result = [];
        if ($this->parent !== null) {
            $result[] = $this->parent;
            $parents = $this->parent->parents;
            if (!empty($parents)) {
                $result[] = $this->parents;
            }
        }
        return $result;
    }

Wrong string
$result[] = $this->parents;

Should be
$result[] = $parents;

Hello, thank you. You are right. I have already fix it.

@satoved did you use this module with yii2-admin?

Hello,.
Sorry, my previous code is not working too, it breaks on third parent.
The working one:

    public function getParents()
    {
        $result = [];
        if ($this->catParent !== null) {
            $result[] = $this->catParent;
            $parents = $this->catParent->catParents;

            if (!empty($parents)) {
                foreach ($parents as $parent) {
                    $result[] = $parent;
                }
            }
        }
        return $result;
    }

But I'm not sure if it's a beutiful code. Maybe there is more cool solution.

did you use this module with yii2-admin?

Not yet, actually I'm just using some pieces of your code for my Category model. A lot behaviors and modules is a little bit complicated for me.

@satoved can you give some example of your code?

Unfortunately, there is nothing special in my code.
I've just make working your functions catParents, catChildren, etc in my model, and added the functionality to attach image to category by beforeSave and afterSave triggers.

Now I'm trying to make some recursion functions to make nested lists of categories, but it breaks my mind...

@satoved If You need some help, You can write to me by email