John Davidson

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

0 comments
Message:


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?



My Answer:
To add a new temporary item to the NavBar items using isGuest, you can modify the code as follows:

php
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']],
['label' => 'Register', 'url' => ['/user/registration']]
) : (
'
  • '
    . Html::beginForm(['/user/logout'], 'post')
    . Html::submitButton(
    'Logout(' . Yii::$app->user->identity->username . ')',
    ['class' => 'btn btn-link logout']
    )
    . Html::endForm()
    . '
  • '
    )
    ]
    ]);


    This code snippet will display both the "Login" and "Register" links in the NavBar when the user is a guest. When the user is logged in, it will display the "Logout" link as before.

    Make sure to adjust the URLs and labels according to your application's routes and requirements.

    Rate this post

    4 of 5 based on 5852 votes

    Comments




    © 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
    Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us