Creating a template with a Tag

Tsura Andreeva
Mega Sage

Hello community, the question I received it - is it possible when creating a template to add a specific tag as part of the template so that when we use the new template is automatically taged?

Any suggestions or comments are most appreciated. Thank you!

 

2 REPLIES 2

Punit S
Giga Guru

Hi Tsura, 

To add tags via code when a template is applied to a record in ServiceNow, you can use a Business Rule that triggers when a record is inserted or updated with a specific template.

Here's an example of how you could implement this:

  1. Create a new Business Rule in ServiceNow by navigating to "Business Rules" in the left-hand navigation menu and clicking "New".

  2. Give your Business Rule a name and set the Table to the table that you want to add tags to (e.g. "incident").

  3. In the "Advanced" section of the Business Rule form, set the "When to run" field to "After" and select the "Insert" and "Update" options.

  4. In the "Advanced" section, set the "Advanced" field to true and add the following script:

 

(function executeRule(current, previous /*null when async*/) {

  // Check if the record was created or updated with the specific template
  if (current.getValue('sys_template') == '<TEMPLATE_NAME>') {

    // Add the desired tags to the record
    var tagsToAdd = ['tag1', 'tag2', 'tag3'];
    var existingTags = current.tags.toString().split(',');
    for (var i = 0; i < tagsToAdd.length; i++) {
      if (!existingTags.includes(tagsToAdd[i])) {
        current.addTag(tagsToAdd[i]);
      }
    }
    
    // Update the record to save the changes
    current.update();
  }

})(current, previous);

 

In this script, you will need to replace template name with the name of the specific template that you want to trigger the Business Rule. You can also replace tag1, tag2,tag3 with an array of the tags that you want to add to the record.

Save the Business Rule.
Now, when a record is inserted or updated with the specified template, the Business Rule will add the desired tags to the record. Note that this script assumes that the tags you want to add already exist in the system, otherwise they will not be added.

 

Please mark my answer correct/helpful in case it adds value and moves you a step closer to your desired ServiceNow solution goal. 

Thanks,
Punit

Thank you so much for the code and the clear step by step. I will share with my sys admins and if I have any additional questions I will reach back.