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):
person.query();
while (person.next()) {
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
u_date_completed_flagstaff_min_wage_form
checklist.u_date_completed_flagstaff_min_wage_form = date_completed;
checklist.update();
} else {
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:
- https://youtu.be/GtAFuOgnfU8?t=5m38s
- ServiceNow Docs – search page for ‘get(‘
if (person.get(g_form.getValue(‘u_employee’)) {
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
u_date_completed_flagstaff_min_wage_form
checklist.u_date_completed_flagstaff_min_wage_form = date_completed;
checklist.update();
} else {
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();
}