Hello ServiceNow Professionals and Learners, As a ServiceNow developer or administrator, you've likely encountered situations where you needed to copy attachments from one task to another. This endeavour can be essential for streamlining processes and ensuring data consistency.
Today, I'll walk you through a simple script that will accomplish this.
Why Should You Copy Attachments?
Before getting into the specifics, let's grasp the significance of this. In ServiceNow, the Request Item (RITM) is the parent record, and the SC Task is its child. Often, users attach documents to the RITM, thinking it will be visible to all related tasks. However, by default, attachments don't get copied or accessible to the SC Tasks. This can lead to missed information and increased back-and-forth communication. Automating this process can save time and reduce errors.
To achieve this, we'll create a Business Rule that triggers when an attachment is added to an RITM. This rule will then copy the attachment to all associated SC Tasks.
(function executeRule(current, previous /*null when async*/) {
// Add your code here
if (current.hasAttachments())
{
var gr = new GlideRecord('sc_task');
gr.addQuery('request_item',current.sys_id);
gr.query();
while (gr.next())
{
var a = new GlideSysAttachment();
a.copy('sc_req_item',current.sys_id,'sc_task',gr.sys_id);
}
}
})(current, previous);
Let's break down the code step by step:
Check for Attachments
if (current.hasAttachments())
This line checks if the current record (`current`) has any attachments. The `hasAttachments()` method is a built-in ServiceNow method that returns `true` if the record has one or more attachments, and `false` otherwise.
Querying the 'sc_task' Table
var gr = new GlideRecord('sc_task');
gr.addQuery('request_item',current.sys_id);
gr.query();
Here, a new GlideRecord object is instantiated for the 'sc_task' table. GlideRecord is a ServiceNow API for database operations. The script then adds a query to filter records in the 'sc_task' table where the 'request_item' field matches the `sys_id` of the current record. The `gr.query()` method executes the query.
Copying Attachments
while (gr.next())
{
var a = new GlideSysAttachment();
a.copy('sc_req_item',current.sys_id,'sc_task',gr.sys_id);
}
For each record in the 'sc_task' table that matches the query, the script creates a new `GlideSysAttachment` object (which is a ServiceNow API for managing attachments). The `a.copy()` method is then used to copy attachments from the current record in the 'sc_req_item' table to the matching record in the 'sc_task' table.
With this functionality in place, every time a user attaches a document to an RITM, it will automatically be copied to all associated SC Tasks. This ensures that all necessary information is readily available, streamlining the process for ServiceNow Users.