atif
(atif)
April 25, 2020, 9:44am
1
I am trying to achieve the navbar visibility for a specified user it was working fine when I logged in, the navbar visibility was working until when I logged out there was this error:
Undefined variable: $items
this is where the error is
echo Nav::widget([
‘options’ => [‘class’ => ‘navbar-nav navbar-right’],
‘items’ => $items,
]);
softark
(Softark)
April 25, 2020, 1:36pm
2
Hi @atif , welcome to the forum!
Could you show us the code that runs before these lines, where $items
are defined according to the user permission?
Most probably you have to add
$items = [];
somewhere in your code in order to deal with the permissions of a guest user.
atif
(atif)
April 26, 2020, 4:53am
3
Thank you for your reply. Sorry im new in yii, i will really appreciate your help.
This is the code before these lines:
$navItem = [
];
$itemsForAdmin = [
[‘label’ => ‘Home’, ‘url’ => [‘addproduct/index’]],
[‘label’ => ‘User’, ‘url’ => [‘new-user/index’]],
];
$landr = [
[‘label’ => ‘Login’, ‘url’ => [’/site/login’]],
[‘label’ => ‘Register’, ‘url’ => [’/site/register’]],
];
$items = ArrayHelper::merge($navItem, $itemsForAdmin);
if(Yii::$app->user->isGuest){
array_push($navItem, $landr);
}
else {
array_push($navItem, ‘
’. Html::beginForm([’/site/logout’], ‘post’). Html::submitButton(‘Logout (’ . Yii::$app->user->identity->username . ‘)’,[‘class’ => ‘btn btn-link logout’]).Html::endForm(). ‘ ’);
}
if (Yii::$app->user->can(‘admin’)) {
return $items;
}
echo Nav::widget([
‘options’ => [‘class’ => ‘navbar-nav navbar-right’],
‘items’ => $items,
]);
NavBar::end();
?>
softark
(Softark)
April 26, 2020, 9:08am
4
It looks a bit confused.
Try this instead:
$navItem = [
...
];
$itemsForAdmin = [
['label' => 'Home', 'url' => ['addproduct/index']],
['label' => 'User', 'url' => ['new-user/index']],
];
$landr = [
['label' => 'Login', 'url' => ['/site/login']],
['label' => 'Register', 'url' => ['/site/register']],
];
if (Yii::$app->user->can('admin')) {
array_push($navItem, $itemsForAdmin);
}
if(Yii::$app->user->isGuest){
array_push($navItem, $landr);
} else {
array_push($navItem, '<li>'. Html::beginForm(['/site/logout'], 'post').
Html::submitButton('Logout (' . Yii::$app->user->identity->username . ')',
['class' => 'btn btn-link logout']).Html::endForm(). '</li>');
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $navItem,
]);
NavBar::end();
1 Like
atif
(atif)
April 26, 2020, 9:17am
5
Thank you very much! It Worked!!!