Trigger to Warn for Duplicate Attachment Names and Contents in Salesforce


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

Trigger:

/*    Trigger to Warn for Duplicate Attachment Names and Contents    */
trigger DuplicateAttachment on Attachment (before insert)
{
for(Attachment attachmnt:trigger.New)
{
String sql = 'SELECT Name,Description FROM Attachment';
List<Attachment> attach = Database.Query(sql);

for(Attachment temp:attach)
{
if(temp.Name == attachmnt.Name)
{
attachmnt.Name.addError('Duplicate Name. Filename already exists.');
}
if(temp.Description == attachmnt.Description)
{
String str = 'Similar content already exists in ' + temp.Name;
attachmnt.Description.addError(str);
}
}
}
}

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