The CreatorCon Call for Content is officially open! Get started here.

Nia McCash
Mega Sage
Mega Sage

Have you used the applyTemplate() function of the GlderRecord API? 

Did you know that you can create a new record (for example an Incident) using a Template [sys_template] for an entirely different table (like Server CI)?! 🤯

The applyTemplate() function for a GlideRecord accepts the Template [sys_template] name as a string (NOT a template Sys ID). But, out of the box, template names are not unique. 

So it’s possible to have templates with the same name for the same table... or for different tables.
find_real_file.png

 

In my test, the Server [cmdb_ci_server] was the newest, most recent template to be created/updated. 

When I ran the following code:

var newRec= new GlideRecord('incident');
newRec.initialize();
newRec.applyTemplate('TEMPLATE2');
newRec.insert();

 

I noticed that the template for the Server [cmdb_ci_server] was applied to the new Incident. 😱

Here was my Server [cmdb_ci_server] template. It contains template values for fields that exist on the Incident [incident] table and fields that do NOT exist on the Incident [incident] table (eg. CD Speed).

find_real_file.png

 

This is the resulting Incident record. Note the Short description and Assigned to fields are filled in by the template.

find_real_file.png

 

What happened to the CD Speed value?  It seems like it was ignored. I see the following warning in my logs:

find_real_file.png

 

A Better Way

There is an undocumented (so use at your own risk) GlideTemplate class. Shout out to @Kieran Anson for pointing this out to me on the SNDevs slack.

Here’s how the code above would be updated using this class. You can specify the unique Sys ID for the Template [sys_template] record.

var newRec= new GlideRecord('incident');
newRec.initialize();

// Apply the template using the GlideTemplate API 
var template = GlideTemplate().get(‘295bdacb2fa0bc105dcb59ab2799b610’ /* Template Sys ID*/);
if(template != null){
	template.apply(newRec /*GlideRecord to apply Template too*/);
}

newRec.insert();

 

Using the GlideTemplate API, you can ensure the exact template you specify is applied.

Happy coding!

Comments
James Fricker
Tera Guru

GlideTemplate has been documented for a long time on this page
https://docs.servicenow.com/bundle/xanadu-platform-administration/page/administer/form-administratio...

 

It is also worth mentioning GlideRecord.applyEncodedQuery() which can also be used to apply a template to a record.

https://developer.servicenow.com/dev.do#!/reference/api/washingtondc/server_legacy/c_GlideRecordAPI#...

Version history
Last update:
‎06-10-2021 07:53 AM
Updated by: