Search code examples
phpyii2navbaryii2-advanced-appyii2-basic-app

Yii2 -Make dropdown row in navbar disable/readOnly based on user type


Is there someone who can help me? I make a dropdown on of my layout tab menu. this my dropdown.

[
      'label' => '(' . Yii::$app->user->identity->username . ')',
      'items' => [
          ['label' => 'Change Password', 'url' => ['/site/changepassword']],
          ['label' => 'User Setting', 'url' => ['/user']],
          ['label' => 'test', 'url' => ['/leave-record/leave']],
          '<li class="dropdown-header"></li>',
          ['label' => 'Logout', 'url' => ['/site/logout'],
                                'linkOptions' => ['data-method' => 'post']],
      ],
    ],

I've 3 user type in user model. 1. Master Admin 2. Normal Admin 3. Normal User

if Master Admin login, he can access all rows in dropdown. Then if normal admin login row "User Setting" become disable.


Solution

  • for an item you can use the visible attribute assign a proper condition

    eg:

    [
          ['label' => 'Change Password', 'url' => ['/site/changepassword']],
          [
             'label' => 'User Setting', 
              'url' => ['/user'],
              'visible' => Yii::$app->User->can('masterAdmin'),
          ],
     ],
    

    for two user type you could use a $check

    $check = ((Yii::$app->User->can('masterAdmin') || Yii::$app->User->can('admin')) ? TRUE : FALSE;
    

    .

     ...
     'label' => 'User Setting', 
      'url' => ['/user'],
     'visible' =>$check,