H
H
hollanditkzn2017-03-24 12:21:53
Yii
hollanditkzn, 2017-03-24 12:21:53

How not to show menus to certain users?

I have roles in rbac, I need certain menus to be displayed on the main page when a certain role is hit. If you do not use the Nav widget, then I know how to implement it, but there is a lot of code

<?php if (!Yii::$app->user->isGuest && Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId())['admin']->name == 'admin') { ?>
            <li>
                <a href="index.php?r=tovar%2Findex">
                    <span>Товар</span>
                </a>
            </li>
            <?php } ?>

But it is not possible to rewrite also to the widget, even to determine whether it is a guest or not
echo Nav::widget([
        'options' => ['class' => 'nav nav-pills'],
        'items' => [
        ['label' => 'Главная', 'url' => ['zakaz/index']],
        Yii::$app->user->isGuest?
        ['label' => 'Администратор', 'url' => ['zakaz/admin']]:
        false,
        ['label' => 'Дизайнер', 'url' => ['zakaz/disain']],
        ['label' => 'Мастер', 'url' => ['zakaz/master']],
        ['label' => 'Магазин', 'url' => ['zakaz/shop']],
        ],
    ]);

I get this error The 'label' option is required.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-03-24
@hollanditkzn

you can also use the visible property for each item, for example:

echo Nav::widget([
    'options' => [
        'class' => 'nav nav-pills'
    ],
    'items' => [
        [
            'label' => 'Главная',
            'url' => [
                'zakaz/index'
            ]
        ],
        [
            'label' => 'Администратор',
            'url' => [
                'zakaz/admin'
            ],
            'visible' => ! Yii::$app->user->isGuest // отображаем для НЕ ГОСТЯ
        ],
        
        [
            'label' => 'Дизайнер',
            'url' => [
                'zakaz/disain'
            ],
            'visible' => Yii::$app->user->can("seeMenu") // отображает для юзера у которого есть разрешение seeMenu
        ],
        [
            'label' => 'Мастер',
            'url' => [
                'zakaz/master'
            ]
        ],
        [
            'label' => 'Магазин',
            'url' => [
                'zakaz/shop'
            ]
        ]
    ]
]);

M
Maxim Timofeev, 2017-03-24
@webinar

You need to make a rule in rbac, for example "seeMenu", add a rule for the required roles, and then simply:

$items = [];
$items[] = ['label' => 'Главная', 'url' => ['zakaz/index']];
$items[] = ['label' => 'Дизайнер', 'url' => ['zakaz/disain']];
if(Yii::$app->user->can("seeMenu"))
{
$items[] = ['label' => 'Администратор', 'url' => ['zakaz/admin']];
}
echo Nav::widget([
        'options' => ['class' => 'nav nav-pills'],
        'items' => $items
    ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question