1

I want to write an apex trigger to prevent the deletion of attachments. I can think of Org Wide Defaults and Security of this custom object but how can I write a trigger for the same.

3

3 Answers 3

3
  • You can find out if an Attachment looks up to a specific sObjectType using the getSObjectType method on the ParentId value.
    • It's a good idea to add a null check beforehand because otherwise you end up validating that field as required with a NullPointerException instead of the standard validation for required fields.
  • You can validate a trigger record by calling addError.
  • According to Salesforce's own documentation on Triggers, validation should occur in a before trigger.

The Id check should look like:

if (record.ParentId != null && record.ParentId.getSObjectType() == MyObject__c.sObjectType)
2

You need to write a trigger on Attachment object. To identify attachment related to particular custom object you need check ParentId of Attachment.

trigger AttachmentTrigger on Attachment (before delete) {
    for(Attachment objA : Trigger.Old){
        if(/* Specify the condition*/){
            objA.addError('You can not delete attachment');
        } 
    }
}
0

I recommend you to add a trigger in before delete and throw an exception causing deletion fails.

trigger CustomTrigger on Attachment (before delete) {

   for(Attachment a : Trigger.old){
      //sample validation
      if(a.ParentId == 'check for some sobject'){
         a.addError('Record cannot be deleted');
      }
   }
}

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_exceptions.htm

Instead of custom you should use Attachment object: https://help.salesforce.com/HTViewSolution?id=000181538&language=en_US

2
  • 2
    They're trying to validate the Attachment records.
    – Adrian Larson
    Aug 2, 2016 at 12:58
  • Yes, but it´s just the same. Anyway I modified the snippet to Attachment object.
    – D. Cruz
    Aug 2, 2016 at 13:04

Not the answer you're looking for? Browse other questions tagged .