Prevent duplicate attachments when copying

Lisa Silvaroli
Tera Guru

I am using the below BR on the sys_attachment table to copy attachments added to sc_task to their parent RITM. 

(function executeRule(current, previous /*null when async*/) {
 
var id = current.table_sys_id;
  var gr = new GlideRecord('sc_task');
  gr.addQuery('sys_id', id);
  gr.query();
  if(gr.next()){
  var ritm = gr.request_item;	
  GlideSysAttachment.copy('sc_task', id, 'sc_req_item', ritm);
  }

})(current, previous);

I run into issues with the following scenario:

Attachment1 added to sc_task and copied to ritm

Attachment 2 added to sc_task and the BR copies Attachment1 & Attachment2 to ritm 

RITM ends up with Attachment1, Attachment1 & Attachment2. 

How can I get this BR to not copy a attachment that's already been copied?  

5 REPLIES 5

Ankur Bawiskar
Tera Patron

Hi,

easiest solution

1) delete all the attachments from target

2) then allow copy of all files again

Regards
Ankur

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

Ankur Bawiskar
Tera Patron

Hi,

something like this

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

	var id = current.table_sys_id;
	var gr = new GlideRecord('sc_task');
	gr.addQuery('sys_id', id);
	gr.query();
	if(gr.next()){
		var ritm = gr.request_item;	

		// delete all
		var attachment = new GlideSysAttachment();  
		var agr = attachment.getAllAttachments("sc_req_item", ritm);
		while(agr.next()) {  
			attachment.deleteAttachment(agr.getValue("sys_id"));  
		}  

		// then copy
		GlideSysAttachment.copy('sc_task', id, 'sc_req_item', ritm);
	}

})(current, previous);

Regards
Ankur

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

I thought about that but there could be an attachment added directly to the RITM from the end user or different sc_tasks having attachments added. Deleting would replace with just the current addition. I am only trying to prevent duplicates. 

check my below response for the alternative

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