Loading

Add trigger on Attachment and Note

Fecha de publicación: Oct 13, 2022
Descripción
There would be a condition when an action is to be taken on Insert of an Attachment.

For example:
  • One wants to send email to Account Owner when a Note is added with Parent ID as of Account.
  • One wants to update the field on Case with the name of latest Note added on the particular Case.

In these scenarios, we would require a trigger on Note or Attachment object.
Solución
Standard Salesforce functionality does not allow any modification to Note and Attachment object.

In order to create Apex Trigger follow below steps:
1. Inside Developer Console Click "File"
2. New | Apex Trigger
3. Give a name and select "Attachment" or "Note" SObject from drop down

The trigger can also be created/written using Force.com IDE or ANT.

Sample code:
trigger SetTitleToAttachment on Attachment (after insert) {

String Title;
Id pId;

for(Attachment att: Trigger.new){
Title=att.Name;
pId=att.ParentId;
}

List<Case> c=[select Id , Title__c from Case where Id=:pId];

//assuming one record is fetched.
c[0].Title__c=Title;

update c[0];

}
 
Note: We cannot write a trigger on "Attachment" object using the Salesforce.com UI rather we have to use Developer console or VS Code. 
While creating the trigger on Attachment object, we should be careful as it will be triggered for any Standard or Custom Object with Attachments. Thus while writing trigger code, it is better if the logic is specific to the related object. 
Número del artículo de conocimiento

000385957

 
Cargando
Salesforce Help | Article