copy attachment from one table to another

54

Let’s understand this with an example.

Requirement: Copy all the attachment from requested item to catalog task while creation.

Answer:

Step 1: Create after insert business rule on sc_task table and use below script to copy all the attachments from requested item to sc task.

(function executeRule(current, previous /*null when async*/) {
    // Get the parent RITM from the sc_task
    var ritmSysId = current.request_item; // sys_id of the RITM

    if (ritmSysId) {
        // GlideRecord to get attachments of the RITM
        var attachmentGR = new GlideRecord('sys_attachment');
        attachmentGR.addQuery('table_sys_id', ritmSysId); // RITM's sys_id
        attachmentGR.addQuery('table_name', 'sc_req_item'); // RITM's table name
        attachmentGR.query();

        while (attachmentGR.next()) {
            // Copy each attachment to the sc_task
            var attachmentSysId = new GlideSysAttachment().copy(
                attachmentGR.getValue('table_sys_id'),
                'sc_req_item', // Source table (RITM)
                current.getValue('sys_id'),
                'sc_task' // Destination table (SC Task)
            );

            gs.log('Attachment copied: ' + attachmentSysId);
        }
    }
})(current, previous);

 

Step 2: Explanation of the Script

    1. Retrieve the RITM’s Attachments:
      • The sys_attachment table stores all attachments in ServiceNow.
      • The script queries for attachments where:
        • table_sys_id matches the RITM’s sys_id.
        • table_name is sc_req_item (RITM’s table name).
    2. Copy Attachments:
      • Use the GlideSysAttachment().copy() method to copy each attachment from the RITM (sc_req_item) to the SC Task (sc_task).
    3. Log Progress:
      • Logs are added to track successful attachment copying for debugging.

 

Step 3: Test the Functionality

    1. Create an RITM and attach some files to it.
    2. Create an associated SC Task for that RITM.
    3. Check whether the attachments are copied to the SC Task.

Alternative: UI Action

If you want to copy attachments on demand, you can create a UI Action on the sc_task table with the same script logic.

LEAVE A REPLY

Please enter your comment!
Please enter your name here