phpyii2yii2-basic-app

Yii2 How to add a new temporary item to NavBar items using isGuest


I am new to Yii2 and recently downloaded a basic-app version of the framework. There is a code snippet in the "main.php" file:

echo Nav::widget([
    'options' => ['class' => 'navbar-nav navbar-right'],
    'items' => [
        ['label' => 'Main', 'url' => ['/site/index']],
        ['label' => 'Countries', 'url' => ['/country/countries']],
        ['label' => 'About us', 'url' => ['/site/about']],
        ['label' => 'Contacts', 'url' => ['/site/contact']],
        Yii::$app->user->isGuest ? (
                ['label' => 'Login', 'url' => ['/user/login']]
        ) : (
            '<li>'
            . Html::beginForm(['/user/logout'], 'post')
            . Html::submitButton(
                'Logout(' . Yii::$app->user->identity->username . ')',
                ['class' => 'btn btn-link logout']
            )
            . Html::endForm()
            . '</li>'
        )
    ]
]);

where I want to add registration link like this:

Yii::$app->user->isGuest ? (
                ['label' => 'Login', 'url' => ['/user/login']],
                ['label' => 'Register', 'url' => ['/user/registration']]
        ) : (
            '<li>'
            . Html::beginForm(['/user/logout'], 'post')
            . Html::submitButton(
                'Logout(' . Yii::$app->user->identity->username . ')',
                ['class' => 'btn btn-link logout']
            )

I know this peace of code is wrong, but I want to ask, how can I do this in right way?


Solution

  • Your attempt does not work, because you use a ternary operator which allows only for 1 value and not 2 values. Login and Registration are 2 arrays.

    A possible solution:

    // What everybody sees
    $items = [
        ['label' => 'Main', 'url' => ['/site/index']],
        ['label' => 'Countries', 'url' => ['/country/countries']],
        ['label' => 'About us', 'url' => ['/site/about']],
        ['label' => 'Contacts', 'url' => ['/site/contact']],
    ];
    
    // What only guests see
    if (Yii::$app->user->isGuest) {
        $items[] = ['label' => 'Registration', 'url' => ['/user/registration']];
        $items[] = ['label' => 'Login', 'url' => ['/user/login']];
    }
    
    // What logged in users see
    else {
        $items[] = '<li>'
            . Html::beginForm(['/user/logout'], 'post')
            . Html::submitButton(
                'Logout(' . Yii::$app->user->identity->username . ')',
                ['class' => 'btn btn-link logout']
            )
            . Html::endForm()
            . '</li>';
    }
    
    // Echo your navigation
    echo Nav::widget([
        'options' => ['class' => 'navbar-nav navbar-right'],
        'items' => $items,
    ]);