One of the coolest capabilities of ServiceNow is using Javascript to access database records. This is done using the GlideRecord() object. If you’re like Rick, you spent time searching how to use GlideRecord and when you found a solution, you copied and pasted it into your client script and moved onto the next challenge.

I discovered today that the problem with this technique is the first solution I found was not the optimal solution. Fortunately I happened across a TechNow Video that enlightened me on the best way.

In this case, I am trying to get a single user record from the sys_user table. Once I get the record I then use the person’s user_name from the user object to search for a record in a custom table. So here’s the inefficient way I was doing it (not efficient way in orange highlight):

var person = new GlideRecord(‘sys_user’);

person.addQuery(‘sys_id’, g_form.getValue(‘u_employee’));
person.query();
while (person.next())
{

// set variables for the forms & training completion checklist
var d = new Date();
var y = d.getFullYear();
var m = d.getMonth() + 1;
var day = d.getDate();
var date_completed = y + “-” + m + “-” + day;
var checklist = new GlideRecord(‘u_gica_nh_forms_completion_checklist’);
checklist.addQuery(‘u_user_id’, person.user_name);
checklist.query();
if (checklist.next()) { // we found a checklist for this person already

// we need to update this checklist by setting
u_date_completed_flagstaff_min_wage_form
checklist.u_date_completed_flagstaff_min_wage_form = date_completed;
checklist.update();

} else {

// nope, no checklist – this must be the first form they filled out?
checklist.u_employee = g_form.getValue(‘u_employee’);
checklist.u_user_id = person.user_name;
checklist.u_date_completed_flagstaff_min_wage_form = date_completed;
checklist.insert();

}

The better way — use the get() method (see the yellow highlighted code)

sources:

var person = new GlideRecord(‘sys_user’);
if (person.get(g_form.getValue(‘u_employee’)) {

// set variables for the forms & training completion checklist
var d = new Date();
var y = d.getFullYear();
var m = d.getMonth() + 1;
var day = d.getDate();
var date_completed = y + “-” + m + “-” + day;
var checklist = new GlideRecord(‘u_gica_nh_forms_completion_checklist’);
if (checklist.get(‘u_user_id’, person.user_name)) { // we found a checklist for this person already

// we need to update this checklist by setting
u_date_completed_flagstaff_min_wage_form
checklist.u_date_completed_flagstaff_min_wage_form = date_completed;
checklist.update();

} else {

// nope, no checklist – this must be the first form they filled out?
checklist.u_employee = g_form.getValue(‘u_employee’);
checklist.u_user_id = person.user_name;
checklist.u_date_completed_flagstaff_min_wage_form = date_completed;
checklist.insert();

 

}

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.