Trigger Example scenarios:
Trigger Examples 1. Populate contact description when user creates contact
trigger ContactBeforeInsert on Contact (before insert) {
// Trigger.New hold new version of Contacts
for(Contact contact: Trigger.new){
contact.Description = ‘Contact created successfully by using ContactBeforeInsert trigger’;
}
// No Need to write DML statement, trigger. New will be take care.
}
Trigger Examples 2. Populate contact description with modified user name when user updates contact.
trigger ContactBeforeUpdate on Contact (before update) {
// Trigger.New hold new version of Contacts
for(Contact contact: Trigger.new){
contact.Description = ‘Contact updated successfully by ‘+ userInfo.getUserName() ;
}
// No Need to write DML statement, trigger. New will be take care.
}
Trigger Examples 3. How to write a trigger to inject the above 2 scenarios in one trigger
trigger ContactBeforeInsertUpdate on Contact (before insert, before update) {
// Trigger.New hold new version of Contacts
for(Contact contact: Trigger.new){
if(trigger.isInsert){
contact.Description = ‘Contact created successfully by using ContactBeforeInsert trigger’;
}
If(trigger.isUpdate){
contact.Description = ‘Contact updated successfully by ‘+ userInfo.getUserName() ;
}
}
// No Need to write DML statement, trigger. New will be take care.
}
Trigger Examples 4. Throw an error whenever the user try to delete the contact which is not associated to account
trigger contactBeforeDelete on Contact(before delete){
for(Contact contact: trigger.old){
if(contact.accountId == null){
contact.addError(“Hey! You are not authorized to perform this action.”);
}
}
}