Hi Mohit,
Before triggers can be used to update or validate record values before they are saved to the database.
After triggers can be used to access field values that are set by the database (such as a record’s Id or last Updated field) and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue.
Use Before Trigger:
In the case of validation check in the same object.
Insert or update the same object.
In the case of validation check in the same object.
Insert or update the same object.
Use After Trigger:
Insert/Update related object, not the same object.
Notification email.
We cannot use After trigger if we want to update a record because it causes read only error. This is because, after inserting or updating, we cannot update a record.
Insert/Update related object, not the same object.
Notification email.
We cannot use After trigger if we want to update a record because it causes read only error. This is because, after inserting or updating, we cannot update a record.
trigger AccountTrigger on Account (before insert, after insert){
if(Trigger.isBefore){
if(Trigger.IsInsert){
Contact cont = new Contact();
cont.LastName = Trigger.new[0].name;
cont.FirstName = Trigger.new[0].name;
insert cont;
}
else if(Trigger.IsInsert&&Trigger.IsAfter){
Contact cont = new Contact();
cont.LastName = ‘(Updated)’;
cont.FirstName = Trigger.new[0].name+ ‘Updated’;
insert cont;
}
}
}
if(Trigger.isBefore){
if(Trigger.IsInsert){
Contact cont = new Contact();
cont.LastName = Trigger.new[0].name;
cont.FirstName = Trigger.new[0].name;
insert cont;
}
else if(Trigger.IsInsert&&Trigger.IsAfter){
Contact cont = new Contact();
cont.LastName = ‘(Updated)’;
cont.FirstName = Trigger.new[0].name+ ‘Updated’;
insert cont;
}
}
}
No comments:
Post a Comment