How to Populate dynamically a list collector from Script Include

Jaiti Mohammed
Tera Contributor

Hello,

I want a solution where, based on a List Collector field (in this case, "access type"), when the user selects a value, a list of groups/roles assigned to the user should be displayed in another variable (let's call it groups_to_be_removed). The user can then remove the relevant groups/roles from this list.

there is my script include: 

var DXCAccessGroups = Class.create();
DXCAccessGroups.prototype = {
    initialize: function() {},

    GetGroupIdWithRoleReqQual: function(strRole) {
        var arrId = [];
        if (!strRole)
            return this.getAllGroupsAllowed();
        var arrRoles = [];
        if (strRole == 'itsm')
            arrRoles = new DXCRolesPriveleges().getITSMFulfillerRoles();
        if (strRole == 'itbm')
            arrRoles = new DXCRolesPriveleges().getITBMFulfillers();
        if (strRole == 'csm')
            arrRoles = new DXCRolesPriveleges().getCSMFulfillerRoles();
        if (strRole == 'csm_agent' || strRole == 'csm_manager')
            return 'sys_idIN' + this.getCSMGroupId();
        if (strRole == 'csm')
            arrRoles = new DXCRolesPriveleges().getCSMFulfillerRoles();
        if (strRole == 'bus_stakeholder')
            arrRoles = new DXCRolesPriveleges().getBusinessStakeholderRole();
        var arrRolesId = this.getGroupIdWithRole(arrRoles);
        var arrTypesId = this.getGroupWithProperTypes();
        var arr = new ArrayUtil();
        arrId = arr.intersect(arrRolesId, arrTypesId);
        return 'sys_idIN' + arrId;
    },

    getGroupIdWithRole: function(arrRoles) {
        var arrId = [];
        if (arrRoles.length == 0)
            return '';
        var roles = new GlideRecord('sys_group_has_role');
        roles.addQuery('role.name', 'IN', arrRoles);
        roles.query();
        while (roles.next()) {
            arrId.push(roles.getValue('group'));
        }
        return arrId;
    },

    getGroupWithProperTypes: function() {
        var arrId = [];
        var q = 'u_group_typeNOT INactive_directory,AD_KeyUser,TRAS Group^u_group_typeANYTHING';
        var gr = new GlideRecord('sys_user_group');
        gr.addEncodedQuery(q);
        gr.query();
        while (gr.next()) {
            arrId.push(gr.getValue('sys_id'));
        }
        return arrId;
    },

    getAllGroupsAllowed: function() {
        var itsmRoles = new DXCRolesPriveleges().getITSMFulfillerRoles();
        var itbmRoles = new DXCRolesPriveleges().getITBMFulfillers();
        var csmRoles = new DXCRolesPriveleges().getCSMFulfillerRoles();
        var baRoles = new DXCRolesPriveleges().getBusinessStakeholderRole();
        var arr = new ArrayUtil();
        var arrRoles = arr.union(itsmRoles, itbmRoles, csmRoles, baRoles);

        var arrRolesId = this.getGroupIdWithRole(arrRoles);
        var arrTypesId = this.getGroupWithProperTypes();

        var arrId = arr.intersect(arrRolesId, arrTypesId);
        return 'sys_idIN' + arrId;
    },

    getCSMGroupId: function() {
        var arr = [];
        var groupGR = new GlideRecord('sys_user_group');
        groupGR.addEncodedQuery('typeLIKE7cf2f1b41bf0e95054c3fd949b4bcb42'); //keyuser
        groupGR.query();
        while (groupGR.next()) {
            arr.push(groupGR.getUniqueValue());
        }
        return arr;
    },

    getGroupsForDefaultGroupField: function(groups, userId) {
        var itilGroups = '';
        var gr = new GlideRecord('sys_user_grmember');
        gr.addEncodedQuery('user=' + userId + '^group.typeLIKE1cb8ab9bff500200158bffffffffff62^NQuser=' + userId + '^u_default_assignment_group=true');
        gr.query();
        while (gr.next()) {
            itilGroups = itilGroups + "," + gr.group;
        }

        return 'sys_idIN' + groups + itilGroups;
    },

    getUserAssignedGroup: function(userId) {
        var groups = '';
        var gr = new GlideRecord('sys_user_grmember');
        //user=5119d9101b5a19d007c31f8b8b4bcbc7^group.u_group_typeNOT INactive_directory,TRAS Group
        gr.addEncodedQuery('user=' + userId + '^group.u_group_typeNOT INactive_directory,TRAS Group');
        gr.query();
        while (gr.next()) {
            groups = groups + "," + gr.group;
        }
        return 'sys_idIN' + groups;
    },
    getGroupsForUserBasedOnAccessTypes: function(accessTypes, userId) {
        if (!accessTypes || !userId)
            return '';

        var arrAccessTypes = accessTypes.split(',');
        var arrRequiredGroupIds = [];
        var arrUtil = new ArrayUtil();

        // 1. Map Access Types to Required Groups
        for (var i = 0; i < arrAccessTypes.length; i++) {
            var access = arrAccessTypes[i].trim();
            var groupQual = this.GetGroupIdWithRoleReqQual(access); // ex: "sys_idINabc123,def456"

            // Check if groupQual is valid and starts with 'sys_idIN'
            if (groupQual && typeof groupQual === 'string' && groupQual.startsWith('sys_idIN')) {
                var ids = groupQual.substring(8).split(','); // Get the IDs after 'sys_idIN'

                // Validate the IDs before adding to the array
                if (ids && Array.isArray(ids)) {
                    arrRequiredGroupIds = arrRequiredGroupIds.concat(ids);
                } else {
                    // Handle unexpected case where split didn't result in valid IDs
                    console.warn("Invalid groupQual format: " + groupQual);
                }
            } else {
                // Handle case where groupQual is invalid or not in expected format
                console.warn("Invalid groupQual value: " + groupQual);
            }
        }

        // 2. Get user's current groups
        var userGroupIds = this.getUserAssignedGroup(userId);

        // Check if the user group IDs are in the expected string format
        if (typeof userGroupIds === 'string' && userGroupIds.startsWith('sys_idIN')) {
            // Extract the actual group IDs from the string
            userGroupIds = userGroupIds.substring(8).split(','); // Split by comma
        }
        if (!Array.isArray(userGroupIds)) {
            userGroupIds = [userGroupIds];
        }


        // Now, intersect the arrays to find the common group IDs
        var finalIds = arrUtil.intersect(arrRequiredGroupIds, userGroupIds);

        return finalIds;
    },

    type: 'DXCAccessGroups'
};

there is my Reference qualifier : 

javascript&colon; new DXCAccessGroups().getGroupsForUserBasedOnAccessTypes(
  current.variables.access_type_return.join(','), 
  current.variables.access_type_variables.requested_for
);

 

2 REPLIES 2

sahiltelani
Tera Contributor

Hello @Jaiti Mohammed ,

 

For calling a script include in a reference qualifier, you should make it as Client - callable. 

 

Also, when calling it anywhere, use the API name. ex: new scope.script_include_name().method().

 

I haven't checked the code yet. But this is something that needs to be changed first. Do let me know if it works. 

 

Regards,

Sahil

Ankur Bawiskar
Tera Patron
Tera Patron

@Jaiti Mohammed 

share the variable config screenshots for all the variables you are talking about

is the script include function able to get the variable value you are passing?

If the reference qualifier is applied on list collector variable then ensure you add this in variable attributes

ref_qual_elements=access_type;access_type_variables

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader