Thursday, May 1, 2014

Salesforce Trigger On After Insert


If you want to know what is salesforce trigger and when can we have trigger run ,please check my previous post about Salesforce trigger.

In this post i will  be explaining how you can run your trigger after insert of record into database.

Lests take an example.

if you want to send email to someone in your organization  after every new account is created

so you will need
1) Trigger implementation
2) Html email body/template
3) email receipants

Trigger Implementation:

From Setup, click Customize -> Accounts -> Triggers
In the triggers section, click New.
In the trigger editor, delete the default template code and enter this trigger definition:
>
1.  trigger NewAccountCreationSendEmail on Account (after insert)      { 2.           for(Account act: Trigger.New)                {                        //code to send email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String toEmail = "emailid@gmail.com"; String[] toAddresses = new String[] {toEmail}; mail.setToAddresses(toAddresses); mail.setSubject('New Account is created'); String template = 'Hello {0}, \nNew Account has been Created. Here are the details - \n\n'; template+= 'Account Name- {1}\n'; template+= 'Account Owner - {2}\n'; template+= 'Account Contact - {3}\n'; List args = new List(); args.add(toEmail); args.add(act.Name); args.add(act.OwnerId); args.add(act.AccountNumber); String formattedHtml = String.format(template, args); mail.setPlainTextBody(formattedHtml); Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});                }      }
First line of  code defines the trigger

trigger Trigger_Account_Send_Email on Account (after insert)

It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example, this trigger is called NewAccountCreationSendEmail, it operates on the Account object, and runs after new Accounts are inserted into the database. 

Second line in the trigger is for loop of Account records  referenced by contents of a trigger context variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new Accounts that are  inserted.

for(Account act: Trigger.New)

You can use same trigger before insert,you just have to change parameter on first line from "after insert" to "before insert"


No comments: