how can I update legacy(old) records from server side script.

abhaysingh98
Tera Contributor

Hi,

 

I have a string-type field in a form that stores the names of all the empty fields within that form. The names of these empty fields are captured using on load client script. I am able to store empty fields data that are available in the form it is working fine for a new record and when a record is opened or reloaded however it is not saving empty fields data to old records. We need to manually open all the record then it is getting saved in backend but I don't want that manual process I want that all the legacy(old) record should get updated with empty field data automatically. I tried using scheduled job but it was not working.

This is the client Script I have used for storing empty fields data in a string type field.

 

function onLoad() {
    var gaAct = new GlideAjax('x_roho_rwd.getEmptyFields');
    gaAct.addParam('sysparm_name', 'getEmptyFields');
    gaAct.addParam('sysparm_recordSysId', g_form.getUniqueValue());
    g_form.setDisplay('empty_fields', false);

    gaAct.getXMLAnswer(function(response) {

        var array = response.split(",");
        var ind = 0;
        var y = 0;
        var arr = [];
        var clmValue = [];
        for (ind = 0; ind < array.length; ind++) {
            if (g_form.isFieldVisible(array[ind])) {
                arr.push(array[ind]);
            }
        }
        for (y = 0; y < arr.length; y++) {
            var field = g_form.getLabelOf(arr[y]);
            clmValue.push(field);
        }
        //var newValue = arr.join(', ');
        var newValue = clmValue.join(', ');
        g_form.setValue('empty_fields', newValue);
        //g_form.save();

       
        // Call GlideAjax to save the data to the backend
        var gaSave = new GlideAjax('x_roho_rwd.SaveEmptyFields');
        gaSave.addParam('sysparm_name', 'saveEmptyFields');
        gaSave.addParam('sysparm_recordSysId', g_form.getUniqueValue());
        gaSave.addParam('sysparm_emptyFields', newValue);
        gaSave.getXMLAnswer(function(response) {
            if (response === 'success') {
                console.log('Empty fields saved successfully.');
            } else {
                console.log('Failed to save empty fields.');
            }
        });

    });

}
9 REPLIES 9

Ankur Bawiskar
Tera Patron
Tera Patron

@abhaysingh98 

To update all legacy records with the empty field data automatically, you can use a background script in ServiceNow. This script will iterate through all the records and update the empty_fields field without the need for manual intervention. Here's an example of how you can achieve this:

  1. Create a Script Include to handle the logic for fetching empty fields:
var EmptyFieldsUtil = Class.create();
EmptyFieldsUtil.prototype = {
    initialize: function() {},
    getEmptyFields: function(recordSysId) {
        var gr = new GlideRecord('your_table_name'); // Replace with your table name
        if (gr.get(recordSysId)) {
            var emptyFields = [];
            gr.getFields().forEach(function(field) {
                if (gr[field.getName()].nil()) {
                    emptyFields.push(field.getName());
                }
            });
            return emptyFields.join(', ');
        }
        return '';
    },
    type: 'EmptyFieldsUtil'
};
  1. Create a Background Script to update all records:
updateRecords();

function updateRecords() {
    try {
        var gr = new GlideRecord('your_table_name'); // Replace with your table name
        gr.query();
        while (gr.next()) {
            var emptyFields = new EmptyFieldsUtil().getEmptyFields(gr.sys_id);
            gr.empty_fields = emptyFields;
            gr.update();
        }
    } catch (ex) {
        gs.info(ex);
    }
}

This background script will go through each record in your specified table, determine the empty fields using the EmptyFieldsUtil Script Include, and update the empty_fields field accordingly.

Make sure to test this script in a development or test environment before running it in production to ensure it works as expected and doesn't impact performance.

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

Hi @Ankur Bawiskar ,

 

Getting this error while executing the code in background script.

JavaException: com.glide.script.fencing.MethodNotAllowedException: Function getFields is not allowed in scope x_roho_rwd 

 

@abhaysingh98 

you never told you are in scoped app

getFields() won't work in scoped app

try this

var EmptyFieldsUtil = Class.create();
EmptyFieldsUtil.prototype = {
    initialize: function() {},
    getEmptyFields: function(recordSysId) {
        var gr = new GlideRecord('your_table_name'); // Replace with your table name
        if (gr.get(recordSysId)) {
            var emptyFields = [];
            for (var i in gr) {
                if (gr[i] == '' && !i.toString().startsWith('sys'))
                    emptyFields.push(i.toString());
            }
            return emptyFields.join(', ');
        }
        return '';
    },
    type: 'EmptyFieldsUtil'
};

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

Hi @Ankur Bawiskar ,

 

I have to show only those fields that are visible on the form and are empty your from your script I am getting all the fields that are there in the form.

 

I already have a script include and client script that are setting this field value when form is loaded now the issue is that I have to load all the tickets manually so is there any way I can load all the legacy records so that it will update automatically.