Saturday, 5 April 2014

How to write a trigger on Attachment object

Hey !  Lets  work on the object which is less used in salesforce i. e am talking about Attachment object !

What is Attachment object ?

Attachment is standard object provided by the salesforce. Interesting thing is you will not find this object under customise tab in salesforce UI. But if you are aware of workbench then through that you can easily come to know the objects which are available in salesforce . Any ways lets get ahead .


Attachment objects is available under the Account Object related list.

Now, Lets run towards writting a trigger on attachment object. So, let me just walk you through the scenario first.
Scenario is :- Say , we want to update an field named last attachment .Every time the attachnment is added. It is very simple to write a trigger whcih is hardly a 10 lines code .
 Here , is the trigger :-


trigger LastAttach on Attachment (After insert) {
    list<account> aclist= new  list<Account>() ;
    Account ac= new Account();
    for (attachment a : trigger.new ){
    
        aclist.add( new Account(Id=a.ParentId ,AnkushTest__last_attachment_added__c= System.now()));
    
            }
  //}
    update aclist;
    }


Dont worry lemme explain it what i did line by line :-

So , in the very first step I created the list of account , then I tried to iterate each attachment till it is created . 
Now, the intersting point here is to note that Account is the parent of attachment object . So, I just have to pick the parent ID and Assigning it to the Account Id. Then a very simple step to have the time stamp of current time used system.now() which returns the current time. 


Happy Coding !!!!
Ankush
ankushsalesforce@gmail.com











No comments:

Post a Comment

oAuth Use Case -  Headless API Explained in the Easiest way Wondering why? and When we use the Headless API flow Use case example: Imagine a...