The CreatorCon Call for Content is officially open! Get started here.

User is in multiple groups, but query only returns one group

Bruler1230
Tera Expert

I have a script include that needs to return the groups that a user is a member of. Currently my script inlcude is only returning one group, even if there are 3 groups total? Why is my query only getting one group?

 

var currentUser = this.getParameter('sysparm_user')
var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('user', currentUser);
gr.query();

if (gr.next()) {
var groupname = [];
var group = new GlideRecord('sys_user_group');
group.addQuery('sys_id', gr.group);
group.query();

while(group.next()) {
groupname.push(group.name.toString();
}
return groupname.toString();
}
7 REPLIES 7

Update...on the portal, in an alert, i get the values of all of the groups using your example. But still only one of them displays in the field. This is a multi line text field that the groups need to populate into.

Thanks.

Community Alums
Not applicable

Hi, 

Could you share the full code that you're using to display the code in the portal (if it's in a widget, both the server side and client side scripts)?

The community will then hopefully be able to support you with this. 

Mike

ryan_pope
Mega Guru
var gr = new GlideRecord('sys_user_grmember');
gr.addQuery('user', currentUser);
gr.query();

//This was in the while loop. I moved it out so it persists through the loop
var groupname = [];

// YOUR LINE if (gr.next()) {
while(gr.next()) {
//move this outside of the while var groupname = [];

//NOT NEEDED var group = new GlideRecord('sys_user_group');
//NOT NEEDED group.addQuery('sys_id', gr.group);
//NOT NEEDED group.query();

//NOT NEEDED while(group.next()) {
groupname.push(group.name.toString();
//NOT NEEDED }
//NOT NEEDED return groupname.toString();
}

From here, you have access to the array "groupname" to do what you need.