+ Start a Discussion
Abby StockerAbby Stocker 

Prevent duplicate files on a record

Hello! Here is the problem:

The process is the representaive will email the client asking for photos of damage. The client will then email back including 3 photos. Those 3 photos (and the email signature photo..ugh) will attach to the case as 3 related files
Now the representative will forward that email to the appropriate person (not always a SF user) but those three photos will attach again to the case as files. So now there are 6 photos (duplicates). When I delete one, it will delete its duplicate as well. 
Is there a way to stop this? Is there a trigger I can use that will not save the file to the record if a file of the same name and size already exists?? Thank you! 
VinayVinay (Salesforce Developers) 
Hi Abby,

You can prevent based on duplicate attachment names.

Please find below sample code for reference.

trigger DuplicateAttachment on Attachment (before insert) {
 
 Set < String > setAttNames = new Set < String >();
 Map < String, Attachment > mapAttachment = new Map < String, Attachment >();

 for ( Attachment attachmnt:trigger.New ) {
  setAttNames.add(attachmnt.Name);
 }

 for ( Attachment att : [ SELECT Id, Name FROM Attachment WHERE Name IN: setAttNames ] ) {
  mapAttachment.put(att.Name, att);
 }

 for ( Attachment attachmnt : trigger.New ) {
  if ( mapAttachment.containsKey(attachmnt.Name) ) { 
   attachmnt.Name.addError('Duplicate Name. Filename already exists for attachment id ' + mapAttachment.get(attachmnt.Name) + '.'); 
  }
 }

}

https://help.salesforce.com/articleView?id=000330418&type=1&mode=1

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar