apex trigger in salesforce

Apex Trigger In Salesforce - The Developer Guide

Apex Trigger in Salesforce

A trigger is an Apex script which executes before or after DML events occur. Apex triggers enable you to work on custom steps of after and before logics to data in Salesforce. It works insertions, updates, or deletions. As database systems support triggers, Apex also allows triggers to support managing records. 

Syntax of the Trigger:

trigger Trigger_Name on Object_Name (trigger_events)
{
    codeblock
}

dont miss out iconDon't forget to check: Salesforce Apex Trigger - Count Number of Open Tasks and Closed Tasks on the Account.

Trigger’s Events:

There is various type of list of events in trigger which execute the set of statements in Salesforce which are given as follows:

before insert

before update

before delete

after insert

after update

after delete

after undelete   

Context Variable:

isInsert: It returns the true value if insert operation is performed in Salesforce Org.

Isupdate:It returns the true value if update operation is performed in Salesforce Org.

isDelete: It returns the true value if delete operation is performed in Salesforce Org.

isExecute: It returns the true value if execute operation is performed in Salesforce Org.

isUndelete: It returns the true value if undelete operation is performed in Salesforce Org.

isAfter: It returns the true value if after operation is performed in Salesforce Org.

isBefore:> It returns the true value if before operation is performed. in Salesforce Org.

trigger.New:It returns the list of new versions of sObjects records over which operations are performed in Salesforce Org..

trigger.Old:It returns the list of old versions of sObjects records over which operations are performed in Salesforce Org..

newMap in Trigger:

newMap is a map of IDs which have the new versions of records in the form of sObjects. newMap is only available before update, after insert, after update, and after undelete triggers in Salesforce Org..

oldMap in Trigger:

oldMap is a map of IDs that have the old versions of records in the form of sObjects. oldMap is only available to update and delete triggers.

Bulkify Trigger:

A trigger is capable of handling or working on multiple records, this type of trigger is known as bulkifying trigger. When a batch of records starts Apex, a single instance of that Apex code is executed, but it is required to support all of the records in this batch. This is the type of trigger which operates on collections of sObjects and which perform efficient SOQL and DML operations in Salesforce org. It does not cross the Governor Limits and follow the best Practices.

Example of Trigger:

Created type 1 and type 2 two record type on Opportunity object and there are custom fields ‘Amount’ on opportunity.

Create two custom fields on Account ‘Amount 1’ and ‘Amount 2’.

Write an apex trigger for INSERT, UPDATES and DELETE, if the user INSERT in the amount field of type 1 Opportunity and type 2 Opportunity then these amounts should INSERTto Amount 1 field of Account and Amount 2 field of Account respectively.

dont miss out iconCheck out another amazing blog by Aditya here: Salesforce Visualforce Vs Salesforce Lightning Component

If the user UPDATES the amount field of type 1 Opportunity and type 2 Opportunity then these amounts should UPDATE to the Amount 1 field of Account and Amount 2 field of Account respectively.

If the user DELETE in the amount field of type 1 Opportunity and type 2 Opportunity then these amounts should DELETE to the Amount 1 field of Account and Amount 2 field of Account respectively.

//code:

trigger TriggerOnOpportunityToUpdateAccountAmount on Opportunity (after insert, before update, after update, before delete) {    
    set<ID> accountId = new set<ID>();
    list<Account> accList = new list<Account>();
    Id recordType1Id = Schema.SObjectType.Opportunity.RecordTypeInfosByName.get('Type 1').RecordTypeId;
    Id recordType2Id = Schema.SObjectType.Opportunity.RecordTypeInfosByName.get('Type 2').RecordTypeId;
    if((trigger.isInsert || trigger.isUpdate) && (trigger.isAfter)){
        for (Opportunity opp:trigger.New){            
            accountId.add(opp.AccountId);
        }
    }
    if((trigger.isDelete || trigger.isUpdate) && (trigger.isBefore)){
        for (Opportunity opp:trigger.Old){            
            accountId.add(opp.AccountId);
        }
    }
    Map<id, Account> accMap = new Map<id, Account> ([SELECT id, name, Type_1_Total_Amount__c,Type_2_Total_Amount__c from Account where id In :accountId]);
    //if trigger is on inserted
    if(trigger.isInsert){
        for (Opportunity opp:trigger.New){          
            if(opp.AccountId != null && opp.Amount != null){
                if (opp.RecordTypeId == recordType1Id) {                   
                    if(accMap.get(opp.AccountId).Type_1_Total_Amount__c !=null){
                        accMap.get(opp.AccountId).Type_1_Total_Amount__c = opp.Amount + accMap.get(opp.AccountId).Type_1_Total_Amount__c;
                        accList.add(accMap.get(opp.AccountId));                                             
                    }else{
                        accMap.get(opp.AccountId).Type_1_Total_Amount__c = opp.Amount;
                        accList.add(accMap.get(opp.AccountId)); 
                    }
                }
                if(opp.RecordTypeId == RecordType2Id){
                    if(accMap.get(opp.AccountId).Type_2_Total_Amount__c !=null){
                        accMap.get(opp.AccountId).Type_2_Total_Amount__c = opp.Amount + accMap.get(opp.AccountId).Type_2_Total_Amount__c;
                        accList.add(accMap.get(opp.AccountId));
                    }else{
                        accMap.get(opp.AccountId).Type_2_Total_Amount__c = opp.Amount;
                        accList.add(accMap.get(opp.AccountId)); 
                    } 
                }
            }            
        }        
    }
    //trigger is on after update
    if(trigger.isUpdate){
        
        if(trigger.isAfter){
            for(opportunity opp:trigger.new){
                if(opp.AccountId != null && opp.Amount != null){
                    if (opp.RecordTypeId == recordType1Id) {                        
                        accMap.get(opp.AccountId).Type_1_Total_Amount__c = accMap.get(opp.AccountId).Type_1_Total_Amount__c + opp.Amount - trigger.oldMap.get(opp.id).Amount;
                        system.debug('$$$$$$$$$$$');
                        accList.add(accMap.get(opp.AccountId));                                 
                    }
                    if(opp.RecordTypeId == RecordType2Id){
                        accMap.get(opp.AccountId).Type_2_Total_Amount__c = accMap.get(opp.AccountId).Type_2_Total_Amount__c + opp.Amount - trigger.oldMap.get(opp.id).Amount;
                        accList.add(accMap.get(opp.AccountId));                        
                    }
                } 
            }
            upsert accList;
        }
        //triger on Before update
        if(trigger.isBefore){
            system.debug('Batch Started');	
            // batch class calling            
            UpdateOpportunityClosedDate updateOpp = new UpdateOpportunityClosedDate();
            Id batchId = Database.executeBatch(updateOpp);
            system.debug('Batch Id:::::::'+batchId);
        }
    }    
    //trigger is on before delete
    if(trigger.isDelete){
        for(opportunity opp : trigger.Old){
            if(opp.AccountId != null && opp.Amount != null){
                if (opp.RecordTypeId == recordType1Id){
                    accMap.get(opp.AccountId).Type_1_Total_Amount__c = accMap.get(opp.AccountId).Type_1_Total_Amount__c - opp.Amount;
                    accList.add(accMap.get(opp.AccountId));
                }
                if(opp.RecordTypeId == RecordType2Id){
                    accMap.get(opp.AccountId).Type_2_Total_Amount__c = accMap.get(opp.AccountId).Type_2_Total_Amount__c - opp.Amount;
                    accList.add(accMap.get(opp.AccountId));
                }
            } 
        }
    }
    update accList;    
}

Related Articles

Responses