
- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 06-10-2021 07:53 AM
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.
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).
This is the resulting Incident record. Note the Short description and Assigned to fields are filled in by the template.
What happened to the CD Speed value? It seems like it was ignored. I see the following warning in my logs:
A Better Way
There is an undocumented (so use at your own risk) GlideTemplate class. Shout out to
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!
- 3,847 Views
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
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.