Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Better way to write this script instead of Else If Statement

psyherin
Kilo Sage

Hi ,

I'm new to scripting and having trouble wrapping my head around this one. If there is a better way to script it instead of using ELSE IF

I am trying to restrict records using a before query business rule.

 

var qu = '';

if(gs.getUser().hasRole("admin") || gs.getUser().isMemberOf('287ee6fea9fe198100ada7950d0b1b73')) {
qu = current.addEncodedQuery("");
}
else if (gs.getUser().hasRole("itil") && !gs.getUser().isMemberOf('287ee6fea9fe198100ada7950d0b1b73')) {
qu = current.addEncodedQuery('cat_item!=c0c5b2db4fbf4200086eeed18110c718');
}
else if (gs.getUser().hasRole("itil") && !gs.getUser().isMemberOf('123ee6fea9fe198100ada7950d0b1b73')) {
qu = current.addEncodedQuery('cat_item!=c0c5b2db4fbf4200086eeed18110c718');
}
else if (gs.getUser().hasRole("itil") && !gs.getUser().isMemberOf('789aaafea9fe198132ada7950d0b1b73')) {
qu = current.addEncodedQuery('cat_item!=c0c5b2db4fbf4200086eeed18110c718');
}

return;
1 ACCEPTED SOLUTION

Got it. OR'ing the isMemberOf's into a single line with the itil role check should work well for you.

View solution in original post

9 REPLIES 9

Logan Poynter
Mega Sage
Since your actual qu variable is the same and the itil role is required on all of them, just OR ( || ) the isMemberOf's together. What is it you're attempting to do exactly? There may be a better solution.

I am trying to restrict records using a before query business rule for specific groups. The case is where we dont want to allow specific group of users to have access to the (RITM & SCTASK) records created from catalog.

We dont want to take path of ACL and using BR is good practice.

Got it. OR'ing the isMemberOf's into a single line with the itil role check should work well for you.

Is this correct now ?

var qu = '';

if(gs.getUser().hasRole("admin") || gs.getUser().isMemberOf('sys_id') || gs.getUser().isMemberOf('sys_id') || gs.getUser().isMemberOf('sys_id')) {
qu = current.addEncodedQuery("");
}
else if (gs.getUser().hasRole("itil") && !gs.getUser().isMemberOf('sys_id') || !gs.getUser().isMemberOf('sys_id') || !gs.getUser().isMemberOf('sys_id')); {
qu = current.addEncodedQuery('cat_item!=c0c5b2db4fbf4200086eeed18110c718');
}