There are scenarios in Salesforce where you need to perform an action automatically when an Attachment or Note is added to a record. Standard Salesforce functionality does not support automation rules (such as Workflow Rules or Process Builder) directly on the Attachment or Note objects.
However, you can use an Apex trigger to accomplish this.
Common Use Cases
In these scenarios, an Apex trigger on the Note or Attachment object is the supported approach.
Alternatively, you can create the trigger using VS Code with the Salesforce Extension Pack by running the "SFDX: Create Apex Trigger" command, or using the Force.com ANT Migration Tool.
The following describes the logic for a trigger that updates a Case's custom Title field with the name of the most recently attached file. When a new Attachment record is inserted, the trigger reads the Attachment's Name (the file name) and its ParentId (the ID of the record the file was attached to). It then queries the Case record where the Case ID matches the ParentId and updates the Case's custom Title__c field with the Attachment's Name.
The trigger includes a check to ensure it targets only Case parent records. This is essential because Attachment triggers fire for all parent object types — without this check, the trigger would attempt to query Cases for Attachments added to Accounts, Contacts, Opportunities, or any other object, which would produce incorrect results or errors.
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];
}
000385957

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.