Error when obtaining sys id of an empty record.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-26-2023 03:18 AM
Hi,
There is a script in our instance where we get sys_id of the location (reference field) from the user table by providing the user sys_id. We are doing it by GlideQuery. This is working fine when there is a location field value on user record but it shows an error when the location is not empty. How do we wrap this below mentioned code in 'if' statements so that this works only when there is a non empty location and returns "undefined" when location is empty instead of showing an error.
var result = 'undefined';
var userSysId = '3dad0f311bc12110bd5cf0e4464bcb67'; //sample user record
var userRecord = new GlideQuery('sys_user')
.get(userSysId, ['location.sys_id'])
.orElse(undefined);
if (userRecord) result = userRecord.location.sys_id;
gs.print(result);

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-26-2023 07:20 AM
Hi @Pranavi2
I'm curious why you're using GlideQuery here instead of GlideRecord? If you switch it to GlideRecord you can pretty easily get the location sys_id or return undefined if one does not exist.
var result = 'undefined';
var userSysId = '0a826bf03710200044e0bfc8bcbe5d7a'; //sample user with location
//var userSysId = 'a8f98bb0eb32010045e1a5115206fe3a'; //sample user without location
var userRecord = new GlideRecord('sys_user');
userRecord.get(userSysId);
var loc_sysID = userRecord.getValue('location');
if (loc_sysID){
result = loc_sysID;
}
gs.print(result);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-26-2023 08:01 AM
Try this out. Should return null for empty location references this way.
var result;
var userSysId = '3dad0f311bc12110bd5cf0e4464bcb67';
var userRecord = new GlideQuery('sys_user')
.get(userSysId, ['location.sys_id'])
.orElse(undefined);
if(userRecord && userRecord.location !== null){
result = userRecord.location.sys_id;
} else {
result = userRecord.location;
}
gs.print(result);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-26-2023 08:14 AM
Hi @Pranavi2 ,
Good day to you!!!
Checkout the simple and efficient way to achieve,
var result = 'undefined';
var userSysId = '0a826bf03710200044e0bfc8bcbe5d7a'; //sample user with location
//var userSysId = 'a8f98bb0eb32010045e1a5115206fe3a'; //sample user without location
var userRecord = new GlideRecord('sys_user');
userRecord.get(userSysId);
if (userRecord.location)
result = userRecord.location;
gs.print(result);
Please hit the helpful and correct answer if my response is really helpful to you...
Thanks & Regards,