For the longest time, the go-to method for copying attachments across various records in ServiceNow has been business rules utilising the GlideSysAttachment class. But this approach usually backfires when we try to copy attachments bi-directionally, giving rise to duplicate attachments. Let’s learn how we can better handle the copy of attachments using sub-flows instead.
Requirement
When an attachment is added to any Incident [incident] record,
- copy the attachment to the parent incident.
- copy the attachment to any child incidents.
Sub-flow configuration
- Navigate to Flow Designer / Workflow Studio and proceed to create a new sub-flow.
- Set the sub-flow to run as ‘System User’.
- The sub-flow needs just two inputs
- reference to the attachment record.
- reference to the target incident record.
- The sub-flow needs just one action, the out-of-box action named ‘Copy Attachment’. Map the sub-flow inputs as inputs to the action as shown below.
- Publish the sub-flow.
- Using the three-dot dropdown, click on ‘Create code snippet’.
- We need to run the sub-flow asynchronously, so just copy the lines 4 through 9 from the popup.
Business rule configuration
- Navigate to Business Rules table and proceed to create a new rule.
- Set the values as follows –
- Name – anything
- Table – Attachment [sys_attachment]
- Advanced – true
- When – async
- Insert – true
- Filter Conditions –
- ‘Table name’ IS ‘Incident’
- AND
- ‘Created by’ IS NOT ‘system’
- Since our sub-flow will run as ‘system’, setting this condition will make sure that the logic is not looping, preventing duplicate attachments.
- Under the ‘Advanced’ tab, the script should look something like below. Notice that the code snippet that we copied from the sub-flow has been written as a re-usable function at the bottom of the script.
- Copyable version of the script can be found here.
Verify the configuration
If all the steps have been followed accurately, any attachments added to an Incident record will get seamlessly copied over to the related parent and child incidents. The business rule and the sub-flow, both will execute asynchronously, thus ensuring that the load on the system will be minimal.
Next steps
Try creating a re-usable sub-flow that can be used to copy attachments to any record irrespective of the table.