Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

Background script to update the List field

Mrman
Tera Guru

Hi All,

I am trying to update the Groups field on the 'user_criteria' table with a list of groups .

Below is the Background script i created ,but this is only updatng one group, bit not the sysid';s mentioned in the array .

Please correct if I am wrong any where.

var grouparray = ["42f1025e1b8b00109604a9b4bd4bcb82","29eb223b57410300eb7cde2edf94f93e","45cf8d011ba700109604a9b4bd4bcb2f"];
for (var i = 0; i < grouparray.length; i++){
var gr = new GlideRecord("user_criteria");
gr.addEncodedQuery('active=true^sys_scope=d4ac3fff5b311200a4656ede91f91af2');
    
gr.query();

while(gr.next()){


gr.group = grouparray[i];
gr.update();
}
}

Once running the script , when I check the User criteria it only shows one group.

1 ACCEPTED SOLUTION

Pradeep Sharma
ServiceNow Employee

Hello Ramamr,

 

Below please find the updated code.

var grouparray = ["42f1025e1b8b00109604a9b4bd4bcb82","29eb223b57410300eb7cde2edf94f93e","45cf8d011ba700109604a9b4bd4bcb2f"];

var gr = new GlideRecord("user_criteria");
gr.addEncodedQuery('active=true^sys_scope=d4ac3fff5b311200a4656ede91f91af2');
    
gr.query();

while(gr.next()){


gr.group = grouparray.join();
gr.update();
}

- Pradeep Sharma

View solution in original post

2 REPLIES 2

Pradeep Sharma
ServiceNow Employee

Hello Ramamr,

 

Below please find the updated code.

var grouparray = ["42f1025e1b8b00109604a9b4bd4bcb82","29eb223b57410300eb7cde2edf94f93e","45cf8d011ba700109604a9b4bd4bcb2f"];

var gr = new GlideRecord("user_criteria");
gr.addEncodedQuery('active=true^sys_scope=d4ac3fff5b311200a4656ede91f91af2');
    
gr.query();

while(gr.next()){


gr.group = grouparray.join();
gr.update();
}

- Pradeep Sharma

BobPaterno
Giga Contributor

You appear to be iterating in the wrong place in the code.  Do the query first, then iterate through each record and increment i as a counter.

For example,

var grouparray = ["42f1025e1b8b00109604a9b4bd4bcb82","29eb223b57410300eb7cde2edf94f93e","45cf8d011ba700109604a9b4bd4bcb2f"];

var gr = new GlideRecord("user_criteria");
gr.addEncodedQuery('active=true^sys_scope=d4ac3fff5b311200a4656ede91f91af2');
gr.query();

var i = 0;

while(gr.next()){
gr.group = grouparray[i];
gr.update();
i++;
}