Welcome to Community Week 2025! Join us to learn, connect, and be recognized as we celebrate the spirit of Community and the power of AI. Get the details  

check if the group has the role contained in a list collector field

JoaoV
Tera Expert

Hi guys,

 

I have a list collector in the group table that has a list of roles in it.

 

I need to check if those roles are already contained in that group (sys_group_has_role table). And if not, assign them.

 

I came up with a business rule in sys_user_group

 

var list = current.list_collector_variable.toString();
var listSplit = list.split(',');

var gr = new GlideRecord("sys_group_has_role");
gr.query("group", "current.sys_id");
gr.query();
while (gr.next()) {
for (var i = 0; i < listSplit.length; i++) {
if (gr.role == listSplit[i]) {
gs.log("duplicated");
} else {
gr.initialize();
gr.group = current.sys_id;
gr.role = arr[i];
gr.insert();

gs.log("created");
}
}
}

 

I have done it in multiple ways, I guess I'm thinking about it in the wrong way, because it is not working as expected.

 

Am I in the right way? Any tip is appreciated!

 

1 ACCEPTED SOLUTION

kamlesh kjmar
Mega Sage

Hi @JoaoV ,

 

Try below script:

 

var group = current.getUniqueValue();
var list = current.getValue('list_collector_variable').split(',');
list.forEach(function(item){
var gr = new GlideRecord("sys_group_has_role");
gr.addQuery("group", group);
gr.addQuery("role", item)
gr.query();
if(!gr.next()){
var grM = new GlideRecord('sys_group_has_role')
grM.initialize();
grM.role = item;
grM.group = group;
grM.insert() 
}
});

I hope this help.

 

Please mark this helpful if this helps and Accept the solution if this solves your issue.

 

Regards,

Kamlesh

 

View solution in original post

4 REPLIES 4

RaghavSh
Mega Patron

what issue are you getting?

two  issue which I can figure out are :

1. for (var i = 0; i <= listSplit.length; i++) // <= instead of < as loop starts from 0

2. gr.role =listSplit[i];     // it should not be arr[i]

 

Please mark the answer correct/helpful accordingly.


Raghav
MVP 2023
LinkedIn

kamlesh kjmar
Mega Sage

Hi @JoaoV ,

 

Try below script:

 

var group = current.getUniqueValue();
var list = current.getValue('list_collector_variable').split(',');
list.forEach(function(item){
var gr = new GlideRecord("sys_group_has_role");
gr.addQuery("group", group);
gr.addQuery("role", item)
gr.query();
if(!gr.next()){
var grM = new GlideRecord('sys_group_has_role')
grM.initialize();
grM.role = item;
grM.group = group;
grM.insert() 
}
});

I hope this help.

 

Please mark this helpful if this helps and Accept the solution if this solves your issue.

 

Regards,

Kamlesh

 

It works great @kamlesh kjmar ! I cannot thank you enough... Been hammering on this all the day!

I am glad, it helped you 🙂