L
L
LemToUp2015-08-25 17:05:31
Yii
LemToUp, 2015-08-25 17:05:31

Yii2 NAV and MENU widgets don't accept an array?

Help me figure it out, you can pass arrays to the Yii2 nav and menu widgets to build a menu.
Without an array, it looks something like this:

'items' => [
                    ['label' => 'Home Page', 'url' => ['site/']],
                    ['label' => 'About Us', 'url' => ['site/about']],
                    ['label' => 'News Events', 'url' => ['site/event']],
                    ['label' => 'Services', 'url' => ['site/service']], 
]

With an array like this:
'items' => [
                    Category::CategoryMenu(),
                ],

And a problem pops up - if the array is one-dimensional, then everything is fine except for one single menu item:
Array ( [label] => Tamen causa ut diam [url] => Array ( [0] => /site/category?id=4 ) )

As soon as I put a multidimensional array, NAV immediately gives an error, MENU does not display anything:
Array ( [0] => Array ( [label] => Appellatio vel hos autem [url] => Array ( [0] => /site/category?id=5 ) ) [1] => Array ( [label] => Consequat [url] => Array ( [0] => /site/category?id=6 ) ) [2] => Array ( [label] => Illum secundum [url] => Array ( [0] => /site/category?id=3 ) ) [3] => Array ( [label] => Illum secundum1 [url] => Array ( [0] => /site/category?id=8 ) ) [4] => Array ( [label] => Nibh valde tincidunt [url] => Array ( [0] => /site/category?id=7 ) ) [5] => Array ( [label] => Tamen causa ut diam [url] => Array ( [0] => /site/category?id=4 ) ) )

The function in which I pull out the array looks like this:
public static function CategoryMenu() {
        $item=[];
        $categories=Category::find()->orderBy('title')->all();
        foreach ($categories as $category) {
            $item[]= array(
                'label'=>$category['title'],
                'url'=>array('/site/category?id='.$category['id'])
        );
        }
        return $item;
    }

I don’t want to transfer the code to the view, but I can’t pull it from the model.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimon, 2015-08-26
@LemToUp

I support Andrey Klyuev , you also set the url not quite correctly (although your option will probably work) in
Try this:

$item['items']= [
                'label'=>$category['title'],
                'url'=>['/site/category', 'id' => $category['id']]
        ];

PS you don't get the correct array structure, the key for the subarray should be 'items'

A
Andrey Klyuev, 2015-08-26
@BBird

Perhaps this is what you need:
'items' => Category::CategoryMenu(),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question