how to add single user to multiple groups

Sanket Pawar
Tera Contributor

I have a list collector field group_access on a catalog item, i need to add a single user i.e requested for on the form to all the groups selected in group_access, how can i do it using script/UI action.

 

I have used below script, but it seems not working, any help will be helpful.

4 REPLIES 4

Anurag Tripathi
Mega Patron

can you paste your script here?

-Anurag

Riya Verma
Kilo Sage

Hi @Sanket Pawar ,

 

Hope you are doing great.

 

we can implement a UI action with a server-side script.

Add User to Groups Table: Catalog Item (sc_cat_item) Client: false Action name: add_user_to_groups

 

we'll write the server-side script for the UI action.. Below is reference script

 

(function() {
  // Get the current catalog item record
  var currentItem = new GlideRecord('sc_cat_item');
  if (currentItem.get(g_form.getUniqueValue())) {
    // Get the requested user from the form field (assuming the field name is "requested_for")
    var requestedUser = currentItem.getValue('requested_for');

    // Get the selected groups from the list collector field (assuming the field name is "group_access")
    var selectedGroups = currentItem.getValue('group_access');

    // Iterate through the selected groups and add the user to each of them
    for (var i = 0; i < selectedGroups.length; i++) {
      var groupSysID = selectedGroups[i].value; // Assuming "value" is the sys_id of the group
      addUserToGroup(requestedUser, groupSysID);
    }
  }

  // Function to add the user to the specified group
  function addUserToGroup(userSysID, groupSysID) {
    var groupMember = new GlideRecord('sys_user_grmember');
    groupMember.initialize();
    groupMember.setValue('user', userSysID);
    groupMember.setValue('group', groupSysID);
    groupMember.insert();
  }

  // Refresh the catalog item form after adding the user to all groups
  g_form.refreshHomepagePane('sc_cat_item', currentItem.getUniqueValue(), currentItem.getView());
})();

 

 
Please mark the appropriate response as correct answer and helpful, This may help other community users to follow correct solution.
Regards,
Riya Verma

Not applicable

Namrata Ghorpad
Mega Sage

Hi @Sanket Pawar ,

Update your script like below.

var grp=current.variables.group_access.toString();
var grpList=grp.split(',');
for(var i=0;i<grpList.length;i++)
{
var grmember=new GlideRecord('sys_user_grmember');
grmember.addQuery('group',grpList[i]);
grmember.addQuery('user',current.variables.request_for_user);
grmember.query();
if(!grmember.next())
{
grmember.initialize();
grmember.setValue('group',grpList[i]);
grmember.setValue('user',current.variables.request_for_user);
grmember.insert();
}
}

 

Please mark my answer as helpful and correct if it helps you.

Regards,

Namrata