Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to cast GlideRecord?

rickseidencdi
Tera Contributor

I'm looking to cast a GlideRecord object into a child class.

What I'm trying to do is fill in a form with a field on cmdb_ci_hardware but I have to do the searching from cmdb_ci.

For example, say that there is a custom field on cmdb_ci_hardware called u_environment.  When I search for a CI, I want to access that field, even though I'm searching from the cmdb_ci table.

I try this

var cmdb_ci=new GlideRecord('cmdb_ci');
cmdb_ci.addQuery('name','SomeHardware');
cmdb_ci.query();
if (cmdb_ci(next)){
  gs.log(cmdb_ci.u_environment);
}

But that returns undefined because the sys_class_name of the cmdb_ci GlideRecord is "cmdb_ci" and the u_environment field is on the cmdb_ci_hardware table.

Is there any way to access that u_environment variable in this case?  I tried doing a query from cmdb_ci and saying Hardware.u_environment is not empty, and it gave "ref_cmdb_ci_hardware.u_environmentISNOTEMPTY".  So I tried cmdb_ci.ref_cmdb_ci_hardware.u_environment, and that crashed my Client Script.

Any help would be appreciated.

 

5 REPLIES 5

sachin_namjoshi
Kilo Patron
Kilo Patron

 

you will have to query cmdb_ci_hardware table instead of cmdb_ci table.

Also, DO NOT use GlideRecord in client script since it will get cause performance issues. Use GlideAjax instead.

 

 

Regards,

Sachin

I'm using g_form.getReference, actually.  But I figured it would be easier to understand using a GlideRecord example.  I'm looking to avoid using a Glide Ajax to return the actual record since it will required a database call to figure out the class of the record, and then another call to get the record in its native class.

I could swear I've seen this done before, but I just can't remember how it was done.

It can't be done using getReference.
If your requirement is onLoad, you could trigger some client-side behaviour with an on display business rule.
The code to "cast" can be seen below:

var sys_id;
var cmdbClass;

var cmdb_ci=new GlideRecord('cmdb_ci');
cmdb_ci.addQuery('name','SomeHardware');
cmdb_ci.query();
if (cmdb_ci.next()){
    sys_id = cmdb_ci.getValue('sys_id');
    cmdbClass= cmdb_ci.getValue('sys_class_name');
}

cmdb_ci = new GlideRecord(cmdbClass);
cmdb_ci.get(sys_id);

ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

You could move the field up to the base table.  Not a great option but stops you from having to do two calls.