AnirudhKumar
Mega Sage
Mega Sage

There are situations when we have to query and get value from a field whose name is dynamic.

Our first thought is to try the below:

var inc = new GlideRecord('incident');
inc.query();

if(inc.next())
{
    var dynamicVariable = 'caller_id';
    return gr.dynamicVariable;//This returns undefined :(
}

 

We can't blame ServiceNow for this because ServiceNow thinks there is a field called dynamicVariable on your table. How do we tell the ServiceNow the dynamicVariable can be any field name???

 

 There are 3 ways to do this:

1. getValue(or getDisplayValue)

var inc = new GlideRecord('incident');
inc.query();

if(inc.next())
{
    var dynamicVariable = 'caller_id';
    return inc.getValue(dynamicVariable); //Returns sysid of the caller :)
}

Note : As you may have guessed , inc.getDisplayValue(dynamicVariable) returns the caller's name

 

2. Square brackets

var inc = new GlideRecord('incident');
inc.query();

if(inc.next())
{
    var dynamicVariable = 'caller_id';
    return inc[dynamicVariable]; //Returns sysid of the caller :)
}

 

3. getElement

var inc = new GlideRecord('incident');
inc.query();

if(inc.next())
{
    var dynamicVariable = 'caller_id';
    return inc.getElement(dynamicVariable); //Returns sysid of the caller :)
}

 

 

Long Live ServiceNow!

Comments
Aman Singh_
Kilo Sage

Thanks much for consolidating it in one Post!!

Daniel Oderbolz
Kilo Sage
You could also mention that the GlideRecord Function isValidField() can be used to check if a (dynamic) field exists.
Version history
Last update:
‎05-22-2021 09:19 AM
Updated by: