Trigger Examples:
What is Trigger? Trigger is piece of code that is executes before and after a record is Inserted/Updated/Deleted from the force.com database.
Trigger Events: Before Insert, Before Update, Before Delete, After Insert, After Update, After Delete and after undelete.
Example 1:
trigger trigEventsTest on Department__c (before insert,after insert,before update,after update) { if(Trigger.isInsert) { system.debug('***IsINSERT*****'); } if(Trigger.isUpdate) { system.debug('******IsUpdate*****'); } if(Trigger.isBefore && Trigger.isInsert) { system.debug('****IsBefore and IsInsert*****'); } if(Trigger.isAfter && Trigger.isInsert) { system.debug('*******IsAfter and IsInsert*****'); } if(Trigger.isBefore && Trigger.isUpdate) { system.debug('*****Before Update******'); } }
Example 2:
Account with Multiple Contacts:
trigger Con5Insert on Account (after insert) { if(Trigger.isAfter) { system.debug('****New Account Record is ******'+Trigger.new); Contact objContact ; List<Contact> lstcon = new List<Contact>(); for(Integer i=1;i<=5;i++) { objContact = new Contact(lastname='AAAAAAAAA'+string.valueof(i),AccountId=Trigger.new[0].Id); lstcon.add(objContact); } system.debug('****List Of Contacts *****'+lstcon.size()); insert lstCon; } }
Example 3:
Trigger.new and Trigger.old
trigger trigEventsTest on Department__c (before update,after update) { if (Trigger.new[0].name != Trigger.new[0].name) { system.debug('*****Value Changed******'); } else { system.debug('*****Value did not change******'); } }
Example 4:
Add Error:
trigger trigEventsTest on Department__c (before insert) { if(Trigger.new[0].name=='India') { Trigger.new[0].name.addError('Name should not be India'); } }