Jump to content

check roles when outputting menu


Macrura
 Share

Recommended Posts

Hi,

I have a frontend menu which is built using pages and a page select; it is output using a function that cycles through the pages and creates the menu; for this menu I wanted to also have the ability to select on some menu items which roles can see those items; I made a new field called menu_roles which selects the role; I didn't use built in roles field because it is permanent and i couldn't get rid of it off one of my templates once i added it.

When i'm cycling through the pages, i'm using this to check if the current user should see the menu:

        $menuVis = true;
        if($child->menu_roles->count()) {        
            foreach($child->menu_roles as $cmr) {
                $menuVis = true;
                $cmrRole = wire('roles')->get("$cmr->name");
                if (!wire("user")->hasRole("$cmrRole") ) $menuVis = false;
            }
        }
        if($menuVis == false) continue;

Edit: this sort of doesn't work... i can't figure out how to check multiple roles against a user at once, to get the visibility variable to be correct...Aarrgh! logic

Link to comment
Share on other sites

Because you want a user to see a menu item if they have one or more, i. e. any of that item’s roles, you want to break out of your foreach as soon as the first matching role is found. Otherwise, any missing role will set $menuVis to false. That would be a good idea if you wanted a user to require all of the item’s roles, in which case you would have to break out of the loop at the first missing role, lest any further iteration sets $menuVis to true again.

if($child->menu_roles->count()) {
    $menuVis = false; //Assume false in case the foreach doesn't find any matching roles and sets it true
    foreach($child->menu_roles as $cmr) {
        $cmrRole = wire('roles')->get("$cmr->name");
        if (wire("user")->hasRole("$cmrRole")) {
            $menuVis = true; //has this role, so no need to check more roles
            break;
        }
    }
}
if($menuVis == false) continue;
  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...