how to populate field of type List using onChange client script with multiple values

Alon Grod
Tera Expert

how to populate field of type List using onChange client script with multiple values

4 REPLIES 4

Abhishek Pal
Giga Guru

Hi @Alon Grod ,

Yes, you can populate multiple values into a List type field from an onChange Client Script.

A List field stores multiple sys_ids from its referenced table.

If you already know the sys_ids, use an array:

function onChange(control, oldValue, newValue, isLoading) {

if (isLoading || !newValue)
return;

var values = [
'SYS_ID_1',
'SYS_ID_2',
'SYS_ID_3'
];

g_form.setValue('u_list_field', values);
}

Replace:

u_list_field

with your List field name.

Important:
The values must be sys_ids from the table referenced by the List field.

For example, if u_users is a List field referencing sys_user:

function onChange(control, oldValue, newValue, isLoading) {

if (isLoading)
return;

if (!newValue) {
g_form.clearValue('u_users');
return;
}

var users = [
'6816f79cc0a8016401c5a33be04be441',
'62826bf03710200044e0bfc8bcbe5df1'
];

g_form.setValue('u_users', users);
}

If the values have to be retrieved dynamically based on the field changed, use GlideAjax.

Example:

Client Script:

function onChange(control, oldValue, newValue, isLoading) {

if (isLoading)
return;

if (!newValue) {
g_form.clearValue('u_users');
return;
}

var ga = new GlideAjax('GetUsersForList');

ga.addParam(
'sysparm_name',
'getUsers'
);

ga.addParam(
'sysparm_value',
newValue
);

ga.getXMLAnswer(function(answer) {

if (!answer) {
g_form.clearValue('u_users');
return;
}

var users = JSON.parse(answer);

g_form.setValue(
'u_users',
users
);
});
}

Client-callable Script Include:

var GetUsersForList = Class.create();

GetUsersForList.prototype =
Object.extendsObject(AbstractAjaxProcessor, {

getUsers: function() {

var value =
this.getParameter('sysparm_value');

var users = [];

var gr =
new GlideRecord('sys_user');

gr.addActiveQuery();

// Add your actual condition here.
// Example:
// gr.addQuery('department', value);

gr.query();

while (gr.next()) {
users.push(
gr.getUniqueValue().toString()
);
}

return JSON.stringify(users);
},

type: 'GetUsersForList'
});

Recommended approach:

onChange field
-> GlideAjax
-> Query required records server-side
-> Return array of sys_ids
-> g_form.setValue()
-> List field populated with multiple records

If instead you want to ADD new values while preserving the values already present in the List field, use:

var existing =
g_form.getValue('u_users');

var values =
existing ? existing.split(',') : [];

values.push('NEW_SYS_ID');

g_form.setValue(
'u_users',
values
);

Before adding values, I would also remove duplicates:

values = Array.from(
new Set(values)
);

Important points:

- The target field must be Type = List.
- Its referenced table must match the sys_ids being supplied.
- Use sys_ids, not names/display values.
- Use GlideAjax when records need to be queried dynamically.
- Do not use client-side GlideRecord for this requirement.
- If you want to replace the existing values, call setValue() directly.
- If you want to preserve existing values, read them first and append the new sys_ids.

ServiceNow officially supports passing an array of sys_ids to g_form.setValue() when the target field is a Glide List.

Hope this helps!

If this response helped, please mark it as Helpful.
If it resolves your issue, please Accept it as Solution.

Kind Regards,
Abhishek Pal

Ankur Bawiskar
Tera Patron

@Alon Grod 

simply set string of comma separated sysIds using g_form.setValue()

what did you try and what didn't work?

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

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

Risto D_od_o
Tera Contributor

I've made this example based on your question and it populates the watch list field with hardcoded IDs. If you want it to be dynamic you should create a script include and then use GlideAjax in your Client Script to return values and populate your field.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    if (oldValue !== newValue) {
        // 1. Define the users you want to add. 
        var usersToAdd = [
            '62826bf03710200044e0bfc8bcbe5df1',
            '800b174138d089c868d09de320f9833b',
            '5137153cc611227c000bbd1bd8cd2005'
        ];
        
        // 2. Get the current watch list values
        var currentWatchList = g_form.getValue('watch_list');
        
        // 3. Convert the comma-separated string into a JavaScript array
        // If the watch list is empty, create a new empty array
        var watchListArray = currentWatchList ? currentWatchList.split(',') : [];
        
        var listUpdated = false;

        // 4. Loop through our new users and check if they are already on the list
        for (var i = 0; i < usersToAdd.length; i++) {
            var user = usersToAdd[i];
            
            // If the user is NOT found in the array, add them
            if (watchListArray.indexOf(user) === -1) {
                watchListArray.push(user);
                listUpdated = true; // Flag that we made a change
            }
        }
        
        // 5. If we actually added someone new, update the field
        if (listUpdated) {
            // .join(',') turns the array back into a comma-separated string
            g_form.setValue('watch_list', watchListArray.join(','));
        }
    }
}

Me Being Mustaq
Kilo Sage

Hi @Alon Grod ,

 

If  the target field is of type List, you can populate it with multiple records in an onChange Client Script by setting a comma-separated list of sys_ids.

Example:

function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading || !newValue) { return; } var users = [ '62826bf03710200044e0bfc8bcbe5df1', '6816f79cc0a8016401c5a33be04be441', '46d44a5dc6112276007f9d0efdb69cd4' ]; g_form.setValue('u_user_list', users.join(',')); }

Notes

  • u_user_list is the name of your List field.
  • The values must be valid sys_ids of records from the table referenced by the List field.
  • Multiple values are passed as a single comma-separated string.
  • If you're setting display values instead of sys_ids, use:
    g_form.setDisplayValue('u_user_list', 'User One,User Two,User Three');
  • If you're receiving values from a GlideAjax call :-

  var ids = answer.split(','); // returned sys_ids g_form.setValue('u_user_list', ids.join(','));

 

Warm Regards,

Shaik Mustaq.