3 ways to GlideRecord a dynamic field name
Import
·
May 22, 2021
·
article
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!
View original source
https://www.servicenow.com/community/now-platform-articles/3-ways-to-gliderecord-a-dynamic-field-name/ta-p/2328268