Search code examples
yii2yii2-basic-app

Yii2 foreach loop inside $menuItems


I have a menu like this

<?php
NavBar::begin([
    'brandLabel' => Html::img('@web/images/cennos1.png', ['alt'=>Yii::$app->name]),
    'brandUrl' => Yii::$app->homeUrl,
    'brandOptions' => ['style' => 'margin-top:-7px;'],
    'options' => [
        'class' => 'navbar-inverse navbar-fixed-top',
    ],
]);  
$menuItems = [];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = [
                    'label' => 'Teams',
                    'items' => [        
                        foreach ($teams as $team) {
                        ['label' => '' . $team->name .'', 'url' => ['team/preview','id' => $team->id]],
                        }
                    ],
                ];

I tried to use foreach loop like that to list all teams as a dropdown menu for guest users to see but it didn't work. Please help me with this. Sorry for my bad English. Thank you.


Solution

  • This may not be the best way, but it works for me.

    function items($teams)
        {
            $items = [];
            foreach ($teams as $team) {
                array_push($items, ['label' => '' . $team->name .'', 'url' => Url::to(['team/preview', 'id' => $team->id])]);
            }
            return $items;
        }
    
    NavBar::begin([
        'brandLabel' => Html::img('@web/images/cennos1.png', ['alt'=>Yii::$app->name]),
        'brandUrl' => Yii::$app->homeUrl,
        'brandOptions' => ['style' => 'margin-top:-7px;'],
        'options' => [
            'class' => 'navbar-inverse navbar-fixed-top',
        ],
    ]);  
    $menuItems = [];
    $menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
    $menuItems[] = [
                        'label' => 'Teams',
                        'items' => items($teams)
                    ];
    

    Hope it helps,