Trigger to Warn for Duplicate Attachment Names in Salesforce

Trigger to Warn for Duplicate Attachment Names in Salesforce

The below trigger is used to warn the users if the Filename of an attachment already exists.

Trigger:

/*    Trigger to Warn for Duplicate Attachment Names    */


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) + ‘.’); 
}
}


}

Leave a Reply