GlideRecord with references


We all know and use GlideRecord.update() and GlideRecord.insert(), but sometimes we would like to do a little more than that, we would like to insert or update data in reference fields as well, now instead of creating a new query to get and update these fields, ServiceNow have created these two wonderful functions to deal with this issue.

There are a few things to take note of when using these methods.
Firstly that the related records are updated first and then the actual record afterwards.
Secondly you need to keep in mind, that if a related record does no exist, one will be created. (In the below sample code, if there are no caller, it will create one with the information provided in the script).
Also if you need to set the value of a reference field on the record, you must set it using the .setDisplayValue() method before manipulating the reference field's values.
Lastly remember to use these methods carefully, as it will update multiple tables at once, if that is what you tell it to do.

GlideRecord.updateWithReferences()

var inc = new GlideRecord('incident');
inc.get(sys_id); //Get incident record based on the sys_id
inc.caller_id.first_name = 'Jesper';
inc.caller_id.email= 'jesper@not-a-real-email.com';
inc.updateWithReferences();

GlideRecord.insertWithReferences()
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'My printer is broken';
inc.caller_id.setDisplayValue('Jesper Testuser'); //Note that if we did not include this line to set the value, a new user would be created
inc.caller_id.first_name = 'Jesper';
inc.caller_id.email= 'jesper@not-a-real-email.com';
inc.insertWithReferences();
Read more about these functions at the ServiceNow Wiki


Comments