Scripted Tags
Tags
As mentioned, Tags are not new. They've been around for a while. Good to know, Tags will be found on lists though not on forms. Tags are also available on (almost) all tables, and immediately available on custom tables.
Data structure
The example above concerns the Incident table. The Tags are actually not stored on the Incident table. Instead, the tags are stored in the Tag table [lable]. The relationship between the Tag and - in case of the example - the Incident table, is stored in the Label Entries table [label_entry].
Key to know:
- Tag [label], "Name" which is unique in case of "Viewable by" other than "Me", and type is "Standard";
- Label Entry [label_entry], which has a reference (Label) to the Tag table, and two string fields (Table and Table key) which contain the Table name and the Sys Id of the record where the Tag is on. In the example above the Table would be "incident". The Target field on the Label Entry will be populated automatically.
Scripting Tags on records
Time to translate the above structure into scripting. For example, we could set up a Business Rule which runs on insert of an Incident. This could well be achieved through the conditions.
For testing, let's say the label we automatically want to add is the "Community article" label.
// Comma seperated list of Tags
var tagsArr = 'Community article';
// Iterate thru the Array and create the Tags and Label Entries
tagsArr = tagsArr.split(',');
for(var i = 0; i < tagsArr.length; i++) {
var tagSysId = '';
var grTag = new GlideRecord('label');
grTag.addActiveQuery();
grTag.addQuery('name', tagsArr[i]);
grTag.addQuery('type', 'standard');
grTag.addQuery('viewable_by', '!=', 'me');
grTag._query();
if(grTag._next()) {
tagSysId = grTag.getUniqueValue();
} else {
grTag.initialize();
grTag.setValue('name', tagsArr[i]);
grTag.setValue('viewable_by', 'everyone');
grTag.insert();
tagSysId = grTag.getUniqueValue();
}
var grTagEntry = new GlideRecord('label_entry');
grTagEntry.initialize();
grTagEntry.setValue('label', grTag.getUniqueValue());
grTagEntry.setValue('table', current.getTableName());
grTagEntry.setValue('table_key', current.getUniqueValue());
grTagEntry.insert();
}
The script itself isn't that huge and difficult. Only two catches:1) Multiple Tags could be entered;
2) To check if the Tag already exists. If so, only a relation (Label Entry) to be created. If not, both a Tag and a relation to be created.
---
And that's it actually. Hope you like it. If any questions or remarks, let me know!
Kind regards,
Mark Roethof
ServiceNow Technical Consultant @ Paphos Group---
https://www.servicenow.com/community/developer-articles/scripted-tags/ta-p/2306155
