The CreatorCon Call for Content is officially open! Get started here.

Auto populate attachment field on portal using script include

BenjaminY
Tera Contributor

I am task with adding three attachment fields to a record producer and having them populate referencing another record producer field (cp_record) on the portal view of the form.

The client script and the client script include I have so far is below, the script is populating the string fields but the three attachment fields I have added are not being populated with the attachment using the reference as it should please advise

 

table (x_g_dh5_ccht_ccht_task)

script include:

 

var CpRecord = Class.create();
CpRecord.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {

    CpRecord: function(recordNum) {
        var num = this.getParameter('sysparm_record_num') || recordNum;
        var gd = new GlideRecord('x_g_dh5_ccht_ccht_task');
        gd.get('number', num);

        // Initialize result object
        var result = {
            'lastName': gd.getDisplayValue('victim_last_name'),
            'firstName': gd.getDisplayValue('victim_first_name'),
            'middleName': gd.getDisplayValue('victim_middle_name'),
            'addressOne': gd.getDisplayValue('victimaddress_line_1'),
            'addressTwo': gd.getDisplayValue('victimaddress_line_2'),
            'alias': gd.getDisplayValue('victim_alias_list'),
            'city': gd.getDisplayValue('city'),
            'state': gd.getDisplayValue('victim_state'),
            'social': gd.getDisplayValue('victim_social_security_number'),
            'coc': gd.getValue('victim_citizenship_country_id'),
            'gender': gd.getDisplayValue('victim_gender_name'),
            'leadFirst': gd.getDisplayValue('lead_officer_first_name'),
            'leadLast': gd.getDisplayValue('lead_officer_last_name'),
            'leadMiddle': gd.getDisplayValue('lead_officer_middle_name'),
            'leadEmail': gd.getDisplayValue('lead_officer_email_address'),
            'leadNum': gd.getDisplayValue('ldc_phone_number'),
            'vwLast': gd.getDisplayValue('victim_relations_last_name'),
            'vwFirst': gd.getDisplayValue('victim_relation_first_name'),
            'vwMiddle': gd.getDisplayValue('victim_relation_middle_name'),
            'vwNum': gd.getDisplayValue('victim_day_time_phone_nbr'),
            'vwEmail': gd.getDisplayValue('victim_relations_email_address'),
            'vwExt': gd.getDisplayValue('victim_relations_phone_ext'),
            'leadExt': gd.getDisplayValue('witness_specialist_phone_ext'),
            'mFirst': gd.getDisplayValue('witness_specialist_first_name'),
            'mLast': gd.getDisplayValue('witness_specialist_last_name'),
            'mMiddle': gd.getDisplayValue('witness_specialist_middle_name'),
            'mEmail': gd.getDisplayValue('ws_email_address'),
            'mNum': gd.getDisplayValue('witness_specialist_day_time_phone_nbr'),
            'mExt': gd.getDisplayValue('witness_specialist_phone_ext'),
            'aNum': gd.getDisplayValue('alien_number'),
            'dob': gd.getDisplayValue('victim_birth_date'),
            'cob': gd.getValue('victim_birth_country_id'),
            'lea': gd.getValue('agency_office_name'),
            'exp': gd.getValue('record_expiration_date'),
            'cCriminal': gd.getDisplayValue('criminal_or_civil_ind'),
            'pDetail': gd.getDisplayValue('civil_action_filing_details_text')
        };

        // Retrieve attachments related to the record (Sys IDs for attachment fields)
        result.victims_complaint_date_time = this.getAttachments('victims_complaint_date_time', gd.sys_id);
        result.litigation_summary_file = this.getAttachments('litigation_summary_file', gd.sys_id);
        result.victims_complaint_file = this.getAttachments('victims_complaint_file', gd.sys_id);

        return JSON.stringify(result);
    },

    // Helper function to get the attachment Sys IDs for a given field
    getAttachments: function(fieldName, recordSysId) {
        var attachmentSysIds = [];
        var attachmentGR = new GlideRecord('sys_attachment');
        attachmentGR.addQuery('table_name', 'x_g_dh5_ccht_ccht_task'); // Replace with the appropriate table
        attachmentGR.addQuery('table_sys_id', recordSysId); // Attachments related to the record Sys ID
        attachmentGR.query();

        while (attachmentGR.next()) {
            // For each attachment, return the Sys ID
            attachmentSysIds.push(attachmentGR.sys_id + ''); // Ensure it returns a string
        }

        return attachmentSysIds; // Return an array of Sys IDs
    },

    type: 'CpRecord'
});
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX End of Script
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
client script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    var recordNum = g_form.getValue('please_provide_the_record_number');
    var ajax = new GlideAjax('CpRecord');
    ajax.addParam('sysparm_name', 'CpRecord');
    ajax.addParam('sysparm_record_num', recordNum);
    ajax.getXMLAnswer(populateCpRecord);

    function populateCpRecord(response) {
        var ans = JSON.parse(response);

        // Populate standard fields
        g_form.setValue('extention_victim_last_name', ans.lastName);
        g_form.setValue('extention_victim_first_name', ans.firstName);
        g_form.setValue('extention_victim_middle_name', ans.middleName);
        g_form.setValue('address_line_1', ans.addressOne);
        g_form.setValue('ext_victim_address_line_2', ans.addressTwo);
        g_form.setValue('extention_victim_alies', ans.alias);
        g_form.setValue('ext_victim_city', ans.city);
        g_form.setValue('ext_victim_state', ans.state);
        g_form.setValue('ext_social_security_number', ans.social);
        g_form.setValue('ext_date_of_birth', ans.dob);
        g_form.setValue('ext_country_of_citizenship', ans.coc);
        g_form.setValue('ext_country_of_birth', ans.cob);
        g_form.setValue('ext_gender', ans.gender);
        g_form.setValue('lead_case_last_name', ans.leadLast);
        g_form.setValue('lead_case_email_address', ans.leadEmail);
        g_form.setValue('lead_case_first_name', ans.leadFirst);
        g_form.setValue('lead_case_phone_number', ans.leadNum);
        g_form.setValue('lead_case_middle_name', ans.leadMiddle);
        g_form.setValue('lead_case_ext', ans.leadExt);
        g_form.setValue('wc_ext_last_name', ans.vwLast);
        g_form.setValue('wc_ext_first_name', ans.vwFirst);
        g_form.setValue('wc_ext_middle_name', ans.vwMiddle);
        g_form.setValue('wc_ext_phone_number', ans.vwNum);
        g_form.setValue('wc_ext_email', ans.vwEmail);
        g_form.setValue('vw_ext_officer', ans.vwExt);
        g_form.setValue('ext_case_agent_last_name', ans.mLast);
        g_form.setValue('ext_case_agent_last_name_first_name', ans.mFirst);
        g_form.setValue('ext_case_agent_middle_name', ans.mMiddle);
        g_form.setValue('ext_case_agent_phone_number', ans.mNum);
        g_form.setValue('ext_case_email', ans.mEmail);
        g_form.setValue('ext_lead_case', ans.mExt);
        g_form.setValue('a_number', ans.aNum);
        g_form.setValue('lead_case_agency_office', ans.lea);
        g_form.setValue('ead_expiration_date', ans.exp);
        g_form.setValue('is_this_civil_or_criminal', ans.cCriminal);
        g_form.setValue('provide_details_of_where_and_when_the_civil_action_was_filed', ans.pDetail);

        // Populate attachment fields
        setAttachmentField('victims_complaint_date_time', ans.victims_complaint_date_time);
        setAttachmentField('litigation_summary_file', ans.litigation_summary_file);
        setAttachmentField('victims_complaint_file', ans.victims_complaint_file);
    }

    // Function to handle setting attachment fields by Sys ID
    function setAttachmentField(fieldName, attachments) {
        if (attachments && attachments.length > 0) {
            var attachmentSysIds = attachments.map(function(sysId) {
                return sysId; // Map each attachment Sys ID
            });
            g_form.setValue(fieldName, attachmentSysIds.join(',')); // Set the Sys IDs as a comma-separated string
        } else {
            g_form.setValue(fieldName, ''); // Clear the field if no attachments
        }
    }
}


 

4 REPLIES 4

Ankur Bawiskar
Tera Patron
Tera Patron

@BenjaminY 

so your current record producer has 3 variables of type file attachment

You have 1 variable which refers to existing record submitted via record producer on same table?

Based on the record selected you want to set the variable value for those 3 attachment variables?

Please share some screenshots.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Yes correct,

 

the three file type fields below are used on two different record producers. I want to use another variable "cp_record" to reference a previously submitted request and populate the 3 attachments fields pm the current record producer once that field"cp_record" is filled.
 victims_complaint_date_time

 litigation_summary_file
  victims_complaint_file

@BenjaminY 

it's very difficult to identify which file was attached to which attachment variable type.

If your record producer has 2 attachment variables then both of them have prefix as ZZ_YY so when you query sys_attachment with this tableName then you won't find it

try with this but this doesn't guarantee the files will be set in correct sequence or with correct variable

attachmentGR.addQuery('table_name', 'ZZ_YYx_g_dh5_ccht_ccht_task'); // Replace with the appropriate table

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Ravi Gaurav
Giga Sage
Giga Sage

Hi @BenjaminY 
 Attachment fields in ServiceNow are typically not directly populated by setting their value to Sys IDs. Instead, attachments are associated with a record through the sys_attachment table, and the UI handles displaying them based on the associated record.

Updated getAttachments Method :-

getAttachments: function(fieldName, recordSysId, targetRecordSysId) {
var attachmentGR = new GlideRecord('sys_attachment');
attachmentGR.addQuery('table_name', 'x_g_dh5_ccht_ccht_task'); // Source table
attachmentGR.addQuery('table_sys_id', recordSysId); // Source record Sys ID
attachmentGR.query();

while (attachmentGR.next()) {
var newAttachment = new GlideRecord('sys_attachment');
newAttachment.initialize();
newAttachment.setValue('table_name', 'x_g_dh5_ccht_ccht_task'); // Target table
newAttachment.setValue('table_sys_id', targetRecordSysId); // Target record Sys ID
newAttachment.setValue('file_name', attachmentGR.getValue('file_name'));
newAttachment.setValue('content_type', attachmentGR.getValue('content_type'));
newAttachment.insert();
}
},

Call the Attachment Copy in the Client Script
ajax.addParam('sysparm_name', 'CpRecord');
ajax.addParam('sysparm_record_num', recordNum);
ajax.addParam('sysparm_target_record_sysid', g_form.getUniqueValue());

--------------------------------------------------------------------------------------------------------------------------


If you found my response helpful, I would greatly appreciate it if you could mark it as "Accepted Solution" and "Helpful."
Your support not only benefits the community but also encourages me to continue assisting. Thank you so much!

Thanks and Regards
Ravi Gaurav | ServiceNow MVP 2025,2024 | ServiceNow Practice Lead | Solution Architect
CGI
M.Tech in Data Science & AI

ï”— YouTube: https://www.youtube.com/@learnservicenowwithravi
ï”— LinkedIn: https://www.linkedin.com/in/ravi-gaurav-a67542aa/