Often, there’s a query about how to create a trigger on Attachment in Salesforce. Specifically, for standard objects like Attachment, ContentDocument, and Note, triggers can’t be created via the Salesforce user interface. However, these triggers can be developed using tools such as the Developer Console or the Force.com IDE. Another option is utilizing the Metadata API.
In this example, we’ll delve into creating a trigger on the Attachment object in Salesforce. To begin with, I’ll explain using the Developer Console. Here are the steps to create a trigger on Attachment using the Developer Console:
- Click on your name (located at the top-left corner) and choose “Developer Console.”
- Navigate to File > New > Apex Trigger.
- Choose the SObject’s name and input the trigger’s name.
- Select the submit button to create the trigger on Attachment.
Similarly, we can create a trigger using the Force.com IDE.
When writing a trigger on Attachment, it’s crucial to exercise caution since it will be utilized by all standard or custom Objects to which an attachment is added. Providing specific criteria for trigger execution ensures it runs only for required objects.
In this example, I’ll create a trigger that checks for the parent object “Account.” If the object is an Account, it will update a field on the Account record.
Trigger snippet:
trigger AttachmentTriggerDemo on Attachment (before insert) { List accountList = new List(); Set accIds = new Set(); for(Attachment att : trigger.New){ //Check if added attachment is related to Account or not if(att.ParentId.getSobjectType() == Account.SobjectType){ accIds.add(att.ParentId); } } accountList = [select id, has_Attachment__c from Account where id in : accIds]; if(accountList!=null && accountList.size()>0){ for(Account acc : accountList){ acc.has_Attachment__c = true; } update accountList; } }