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

}

3 comments:

  1. The select SOQL is written within the trigger.new's "for" loop, What if we have more than 100 records to insert at a time.? Means, we are trying to call the SOQL for more than 100 times, won't that be hitting the governor limits.? Is this the appropriate way to retrieve the details or do we have any other alternative to accomplish this task without hitting governor limits.? Or am I understanding the code in the wrong way.?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. this one
    trigger attachment on attach(before insert)
    {
    string sql ='select Name,Description from attachment';
    list atch =database.query(sql);
    for(attachment a:trigger.new)
    {
    if(a.Name!=null)
    {

    for(attachment aold: atch)
    {
    if(aold.Name==a.Name)
    {
    a.Name.adderror('same name');
    }
    if(temp.Description == attachmnt.Description)
    {
    String str = 'Similar content already exists in ' + aold.Name;
    attachmnt.Description.addError(str);
    }
    }
    }
    }
    }

    ReplyDelete