Dynamic Menu Based On User Roles (Example)

Ever wondered to show the same page but different Menu Options to different users based on their roles? Well, it’s now possible.

In this example, there are 4 Types of User’s & each one is assigned with a Badge. Badges are Upper Management, Admin Staff, Teacher & Student. Members of Upper Management have access to ‘All Pages’ while others have access to few ones only. There is no need to show them other pages if they don’t have access. Hence, four menu’s are created named ‘allmenu’ , ‘adminmenu’ , ‘teachermenu’ & ‘studentmenu’

Note:-

‘allmenu’ is shown by default while rest are ‘hiddenbydefault’.
All Menus are inside the same grid & stretched to max area of same grid.
Code is to be entered in Site Code.
Menu Section is set as Site Master Part.

import wixUsers from 'wix-users';
import wixData from 'wix-data';
$w.onReady(function () {    check();});

wixUsers.onLogin( (user) => {check();} );

function check  () {

 wixData.query("Members/Badges")
            .hasSome("members", wixUsers.currentUser.id)
            .find()
            .then((results) => {
            
 let a = results.items[0].title;

if (a === 'Student') {
    $w('#studentmenu').show();
    $w('#allmenu').hide();
} else if (a === 'Teacher') {
    $w('#teachermenu').show();
    $w('#allmenu').hide();
} else if (a === 'Admin Staff') {
    $w('#adminmenu').show();
    $w('#allmenu').hide();
} else {
    $w('#allmenu').show();
}
                })
                }

Hi @successbedi . Does this code works on the same principle with a role querying one? Your code is searching for member badges and import data, but title claims that it will be executed based on the user roles. As I know, roles and badges differ from each other. Should we use a code like I have added below for the user’s role version? I modified your code a bit.

import wixUsers from'wix-users';

$w.onReady(function(){
     check();
});
wixUsers.onLogin((user)=>{
     check();
});

const check = () => {
wixUsers.currentUser.getRoles()
     .then((roles)=>{
           console.log(roles[0]);
           let userRole = roles.items[0].name;
           if(userRole ==='Student'){
                $w('#studentmenu').show();
                $w('#allmenu').hide();
           } elseif(userRole ==='Teacher'){                               
                $w('#teachermenu').show();
                $w('#allmenu').hide();
           } elseif(userRole ==='Admin Staff'){           
                $w('#adminmenu').show();
                $w('#allmenu').hide();
           } else{
                $w('#allmenu').show();
           }
     });
}

Edit: I wonder if the badge name contains icons, does comparison for userRole works the same? I think it only takes the string parts of them.

Thanks.

Your code works. It worked for me by removing “.items” as indicated below.