Jun 18

Print this Post

Trigger on Attachment in Salesforce

Trigger on Attachment in Salesforce

Many times I have seen question from others that how can we write trigger on attachment in salesforce. For the Attachment, ContentDocument and Note standard objects, we can’t create a trigger in the Salesforce user interface. For these objects, we can create a trigger using development tools, such as the Developer Console or the Force.com IDE. Alternatively, we can also use the Metadata API.

In this example we will learn to write trigger on attachment object in salesforce. Firstly I will explain using developer console. Here are steps to create trigger on attachment using developer console.

1. Click on your name at (top left corner) and Select “Developer Console”

developer console

2. Go to File -> New -> Apex Trigger.

Debeloper Console 2

3. Select name of SObject and enter name of trigger

developer console3

4. Click on submit button. In this way we can create trigger on attachment.

In similar way we can also create trigger using force.com IDE.

We should be very careful while writing the trigger on Attachment, as it will be used by all standard or custom Object on which attachment is added. We should provide criteria to run trigger so that trigger should be executed for required objects only.

In this example I will create the trigger which will check for the parent object “Account”. If the object is Account then it will update one field on account record.

Trigger Code:

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){
    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;

Permanent link to this article: http://www.sfdcpoint.com/salesforce/trigger-on-attachment-in-salesforce/