Wednesday 13 July 2022

Basic Triggers

Apex Trigger is a apex code which will execute before or after DML operation is performed on the database.

There are two types of triggers: Before Triggers, After Triggers.

Before triggers will execute before DML operation is performed on the database. Example validate record values before they’re saved to the database.

After triggers will execute after DML operation is performed on the database. Example - create, update other object records, sending emails.

There are 7 types of trigger events.
Before Insert
Before Update 
Before Delete
After Insert
After Update
After Delete
After UnDelete

Trigger context variables in salesforce

All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.

Here is List of all Trigger Context Variables 

Trigger.isExecuting: Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.

Trigger.isInsert: Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.

Trigger.isUpdate: Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.

Trigger.isDelete: Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.

Trigger.isBefore: Returns true if this trigger was fired before any record was saved.

Trigger.isAfter: Returns true if this trigger was fired after all records were saved.

Trigger.isUndelete: Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)

Trigger.new: Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.

Trigger.newMap: A map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers.

Trigger.old : Returns a list of the old versions of the sObject records. This sObject list is only available in update and delete triggers.

Trigger.oldMap: A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers.

Trigger.size: The total number of records in a trigger invocation, both old and new.

1. Before Insert: Trigger to update Account Description before creation of Account.

Trigger beforeInsertTrigger on Account(Before Insert){

for(Account acc: Trigger.new){
acc.Description = 'Test Description added by beforeInsertTrigger';
}
}

2. Before Update: Trigger to update Account Description before update of Account.

Trigger beforeUpdateTrigger on Account(Before Update){

for(Account acc: Trigger.new){
acc.Description = 'Test Description added by beforeUpdateTrigger';
}
}
trigger beforeUpdateTrigger on Account (before update) {
    for(Account acc: Trigger.new){
        if(acc.Name != trigger.oldMap.get(acc.Id).Name){
            acc.Name.addError('Name cannot be changed.!');
        }
    }
}

3. Before Delete: Trigger to prevent the deletion of Account record if DoNotDelete__c is TRUE.

Trigger beforeDeleteTrigger on Account(Before Delete){

for(Account acc: Trigger.old){
if(acc.DoNotDelete__c){
acc.addError('This record cannot be deleted.!');
}
}
}

4. After Insert: Trigger to create Contact whenever Account is created.

Trigger afterInsertTrigger on Account(After Insert){

List<Contact> listCon = new List<Contact>();
for(Account acc: Trigger.new){
Contact con = new Contact();
con.LastName = acc.Name;
con.AccountId = acc.Id;
listCon.add(con);
}
if(!listCon.isEmpty()){
try {
Database.Insert(listCon, false);
}
catch(Exception exception){
System.debug(Exception ex);
}
}
}

5. After Update: Trigger to create Contact whenever Account is Updated.

Trigger afterUpdateTrigger on Account(After Update){

List<Contact> listCon = new List<Contact>();
for(Account acc: Trigger.new){
Contact con = new Contact();
con.LastName = acc.Name;
con.AccountId = acc.Id;
listCon.add(con);
}
if(!listCon.isEmpty()){
try {
Database.Insert(listCon, false);
}
catch(Exception exception){
System.debug(Exception ex);
}
}

}
6. After Delete: Trigger to dlete Contact records whenever Account is Deleted.

Trigger afterDeleteTrigger on Account(After Delete){

List<Contact> listCon = [SELECT ID FROM Contact Where AccountId =: Trigger.old];
try {
Database.Delete(listCon, false);
}
catch(Exception ex){
System.debug('Exception '+ex);
}
}

7. After Undelete: Apex Trigger to undelete Contacts whenever Account is undeleted.

Trigger afterUndeleteTrigger on Account(After UnDelete){

List<Contact> listCon = [SELECT ID FROM Contact Where AccountId =: Trigger.new];
try {
Database.UnDelete(listCon, false);
}
catch(Exception ex){
System.debug('Exception '+ex);
}
}

trigger AccountUndelete on Account (after undelete) {
    List<Account> accList = new List<Account>();
    for(Account undeletedAccount : [SELECT ID, Name from Account where Id IN : trigger.new]){ 
        undeletedAccount.Name = ('Undeleted :' + undeletedAccount.Name);
        accList.add(undeletedAccount);
    } 
    update accList;
}

Trigger afterUndeleteTrigger on Account(After unDelete){

List<Contact> listCon = [SELECT ID FROM Contact Where AccountId =: Trigger.new and isDeleted=true];
try {
Database.unDelete(listCon, false);
}
catch(Exception ex){
System.debug('Exception '+ex);
}
}
8.