Conditionally build query in script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-11-2023 09:58 AM
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-11-2023 10:15 AM
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().
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-11-2023 10:29 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-16-2023 01:00 PM