Interested in a ServiceNow event built for developers? Registration for now[dev]26 is officially open!

Copy of attachment from variable to record

Tanya10
Tera Contributor

Hi,
I have a variable type attachment on my catalog form. Post submission of request I want to attach that attachment to the requested item so that it shows on the top of the ritm, user doesn't need to scroll down and see for variable attachment
This is what I have tried and it is not working as expected it does copy but every time it copied to ZZ_YYsc_req_item instead sc_req_item

 

var sysID = '72e1e6fbc30d3e5026b5652599013189'; // RITM sys_id


// Get the variables for this RITM
var itemVars = new GlideRecord('sc_item_option_mtom');
itemVars.addQuery('request_item', sysID);
itemVars.query();

while (itemVars.next()) {
    var itemOption = itemVars.sc_item_option; // Points to sc_item_option record
    var variableDef = itemOption.item_option_new; // Points to question definition

    // Check if this is your attachment variable
    if (variableDef == 'ca5cbd8cc3e3a21026b56525990131c6') {
        gs.print('Found attachment variable: ' + variableDef);

        var attachmentGR = new GlideRecord('sys_attachment');
        attachmentGR.addQuery('table_name', 'ZZ_YYsc_req_item');
        attachmentGR.addQuery('table_sys_id', sysID);
        attachmentGR.query();

        while (attachmentGR.next()) {
            gs.print('Copying attachment: ' + attachmentGR.file_name);

            // Copy attachment from variable to RITM
            var newSysId = new GlideSysAttachment().copy(
                attachmentGR.table_name,
                attachmentGR.table_sys_id,
                'sc_req_item',
                sysID
            );

            gs.print('Copied attachment to RITM: ' + newSysId);
        }
    }
}
5 REPLIES 5

Farook Suleman
Tera Contributor

Below tested with one attachment in variable, and copies fine to the RITM:

BR, async, 'insert' ticked, 'advanced' ticked,  [you can add additional filter such as only for specific 'Item']

(function executeRule(current, previous) {
    var attachUtil = new GlideSysAttachment();
    // Query staging attachments for this RITM's variables
    var gr = new GlideRecord("sys_attachment");
    gr.addQuery("table_name", "ZZ_YY" + current.getTableName());
    gr.addQuery("table_sys_id", current.sys_id);
    gr.query();
    while (gr.next()) {
        var content = attachUtil.getContent(gr);
        // Write a clean copy to the RITM itself
        attachUtil.write(
            current,
            gr.file_name.toString(),
            gr.content_type.toString(),
            content
        );
    }
})(current, previous);