Error when obtaining sys id of an empty record.

Pranavi2
Tera Contributor

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);

3 REPLIES 3

Joe S1
Kilo Sage

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);

Claude DAmico
Kilo Sage

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);

 

Claude E. D'Amico, III - CSA

Shanawaz SK
Tera Contributor

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,