logo

NJP

Universal JavaScript Function for Multiple Update from Script

Import · Oct 06, 2019 · article

Every now and then I was in a position where I needed to update multiple records with the same values. This can be done from a ListView but what if I want to update multiple fields for a big number of records? For me, the least time-consuming way of doing it was to run a script in Scripts - Background or Xplore. At first, I was always writing new GlideRecord scripts for different tables. At one point of time, I realized that was writing the same code over and over again with just a few parts of it changing. This was not efficient and for sure I was not following the DRY (Don't Repeat Yourself) rule. So I have written a function that can be used for any table and any field: value pair.

First I have decided that all my field: value pairs I will pass as an array of objects:

[
    { fieldName: 'name of a field', fieldValue: 'new value'},
    { fieldName: 'name of a field', fieldValue: 'new value'},
    .
    .
    .
    { fieldName: 'name of a field', fieldValue: 'new value'}
]

Next, I have decided that the function will need 3 more parameters:

  • name of a table to be updated
  • a query that will point which records should be updated, to be more precise an encoded query (copied from a ListView of a table where filters have been set up)
  • a decision whether or not to run Business Rules

This is how the function looks like:

/*
 * Update multiple items
 *
 * @param tableName {string} - name of a table to find records
 * @param query {string} - query that will be used to find records
 * @param updates {array} - array of objects { fieldName: 'name of a field', fieldValue: 'new value'}
 * @param disableRules {boolean} - enable or disable business rules, false will disable
 *
 */
function updateMultipleRecords(tableName,query,updates,disableRules) {

    if (updates.length > 0) {
        var grItem = new GlideRecord(tableName);
        grItem.addEncodedQuery(query);
        grItem.setWorkflow(disableRules);
        grItem.query();


        updates.forEach(function(item){
            grItem.setValue(item.fieldName,item.fieldValue); // set new values
        });

        grItem.updateMultiple();
    }

}

And this is an example of how to use it:

var updates = [
    { fieldName: 'u_comment', fieldValue: 'this is an multiple update'},
    { fieldName: 'u_select_country', fieldValue: 1 }
];

updateMultipleRecords('u_adobe_systems_users','u_comment=Created by REST API',updates,true);

This is just one way of doing multiple updates. But maybe it will help some people quickly perform the task.

View original source

https://www.servicenow.com/community/developer-articles/universal-javascript-function-for-multiple-update-from-script/ta-p/2324515