The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Conditionally build query in script

Melissa Reed
Tera Contributor

I'm trying to build a script that will conditionally create a query based on the roles a user has.  The user could have multiple roles which would add different conditions to the query.

 

if gs.hasRole('Role1') {

  current.addQuery('sys_id', '12345');

}

 

if gs.hasRole('Role2'){

current.addQuery('sys_id', '98765');

}

 

if gs.hasRole('Role3'){

current.addQuery('sys_id', '76543');

}

 

But if the user has multiple roles, I want it to look like this...

current.addQuery('sys_id', '12345').addOrCondition('sys_id', '98765')

or 

current.addQuery('sys_id', '12345').addOrCondition('sys_id', '76543')

or 

current.addQuery('sys_id', '12345').addOrCondition('sys_id', '98765').addOrCondition('sys_id', '756543')

How can I essentially concatenate parts of the query together conditionally? 

3 REPLIES 3

mrstarlord
Tera Contributor

I don't know if it will work but something you can start with is to create an array to store the conditions that need to be added to the query. Then, for each role that the user has, we add the corresponding condition to the array using push().

After adding all the conditions to the array, we check if the length of the array is greater than 1. If so, we combine the conditions using OR conditions to create a single query using addOrCondition().

Melissa Reed
Tera Contributor

One solution I have tried to set set a flag about whether the query has been created yet or not.

var qFlag='false';

if gs.hasRole('Role1') {

  current.addQuery('sys_id', '12345');

 qFlag ='true';

}

 

if gs.hasRole('Role2'){

if qFlag=='false'{

current.addQuery('sys_id', '98765');

qFlag = 'true';}

else{

current.addOrCondition('sys_id', '98765');}

 

if gs.hasRole('Role3'){

if qFlag=='false'{

current.addQuery('sys_id', '76543');}

qFlag='true';

else{

current.addOrCondition('sys_id', '76543');}

}

 

While this does get down into the else condition, it seems to ignore the addOrCondition.

Melissa Reed
Tera Contributor
for (var i = 0; i < qryARR.length; i++) {
if (i == 0)
{current.addEncodedQuery(qryARR[i]);}
else if (i < qryARR.length-1)
{current.addEncodedQuery('^OR'+qryARR[i]);}
else 
{current.addEncodedQuery('^OR'+qryARR[i]);}
}
 
Anyone know why this doesn't work?  I know the values in qryARR are all different, but it doesn't append to the query when using current.addEncodedQuery (doesn't work if it's addQuery or addOrCondition either).  It sets the first value and never appends.  I've set gs.info statements to log that it is for sure getting into each part of the IF and is changing the value of qryARR[i] but it seems to ignore the addEncodedQuery part.