Monday, January 31, 2022

Real time scenarios of salesforce Trigger

Before going towards directly to real time senario of trigger lets go through basics of trigger

Trigger

Trigger is piece of code that is executes before and after a record is Inserted / Updated / Deleted from the force.com database

Trigger Context Variables:

  • IsInsert:- Returns true if the trigger was fired due to insert operation.
  • IsUpdate:- Returns true if the trigger was fired due to update operation.
  • IsDelete:- Returns true if the trigger was fired due to delete operation.
  • IsBefore:- Returns true if the trigger was fired before record is saved.
  • IsAfter:- Returns true if the trigger was fired after record is saved.
  • New:- Returns a list of new version of sObject records:.
  • Old:- Returns a list of old version of sObject records.
  • NewMap:- Returns a map of new version of sObject records. (map is stored in the form of map).
  • OldMap:- Returns a map of old version of sObject records. (map is stored in the form of map).
  • Size:- Returns a list of new version of sObject records:.
  • isExecuting:- Returns true if the current apex code is a trigger.

Scenarios

  1. create a trigger on account object which will prevent the users in creating duplicate account based on the name
  2. Code

    
    
    trigger AccountDuplicateTrigger on Account (before insert,before update) {
        list accountNames=new list();
        for(Account accountVar:trigger.new)
        {
            accountNames.add(accountVar.name);
        }
        list listOfDuplicateAccounts=[select id,name from Account where name in :accountNames];
        for(Account account:trigger.new)
        {
            if(trigger.isInsert){
            if(listOfDuplicateAccounts.size()!=0)
            {
                account.addError('Account already exists with this name');
            }
            }
            if(trigger.isUpdate)
            {
               for(Account oldaccount :trigger.old)
               {
                   if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0)
                   {
                       account.addError('Account already exists with this name');
                   }
               }
            }
        }
        
    
    }
    
  3. Create trigger Whenever an Account Name is modified send an email notification to the contact of an account.
  4. Code

    
    
    trigger AccountDuplicateTrigger on Account (before insert,before update) {
        list accountNames=new list();
        for(Account accountVar:trigger.new)
        {
            accountNames.add(accountVar.name);
        }
        list listOfDuplicateAccounts=[select id,name from Account where name in :accountNames];
        for(Account account:trigger.new)
        {
            if(trigger.isInsert){
            if(listOfDuplicateAccounts.size()!=0)
            {
                account.addError('Account already exists with this name');
            }
            }
            if(trigger.isUpdate)
            {
               for(Account oldaccount :trigger.old)
               {
                   if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0)
                   {
                       account.addError('Account already exists with this name');
                   }
               }
            }
        }
        
    
    }
    
  5. Create trigger on event object to avoid sessions overlap .
  6. Code

    trigger validateoverlap on Session__c(before insert)
    {
    Set eventID = set();
    for(Session__c sNew : trigger.new)
    {
         //Eent Reference field
         eventID.add(sNew.Event__c);
    }
    List ExistingSessionList = [Select StartDate__c , EndDate__c from Session__c where event__c in : eventID];
    
    for(Session__c sNew : trigger.new)
    {
    
      for(Session__c sOld : ExistingSessionList)
       {
        if(sNew.StartDate__c >= sOld.StartDate__c && sNew.StartDate__c  <= sOld.EndDate__c)
        {
          sNew.addError('Overlap Session');
        }
       }
    }
    }
    
  7. Write trigger to throw error when account is inserted with IsActive(Checkbox) field is True It should always FALSE
  8. TRIGGER

    trigger AccountTriggerToCheckValidation on Account (before insert) {
        if(trigger.IsInsert && trigger.IsBefore) {
            AccountTriggerToCheckValidation_handler.checkIsActiveField(trigger.new);
        }
    }
    
    

    CLASS HANDLER

    public class AccountTriggerToCheckValidation_handler {
        public static void checkIsActiveField(List accList) {
            try{
                if(accList.size() > 0) {
                    for (Account ac : accList) {
                        if (ac.IsActive__c == true) {
                            ac.addError('This Account cannot be created with  IsActive = true.');
                        }
                    }
                }
            } catch(Exception e) {
                System.debug('The following exception has occurred: ' + e.getMessage());
                System.debug('The following Line : ' + e.getLineNumber());
            }
        }
    }
    
    
    
  9. 2 objects Account and Dsignation
    
    parent object: Account
    
    Child object: Designation
    
    Relationship: Lookup(Field name Account__c on Designation object)
    
    If an Account has Designation with Title CEO(Field name Title__c) then the Account field "Area__c" cannot be blank.
    
  10. TRIGGER

    trigger demo on Account (after update) {
       if(trigger.isAfter && trigger.isUpdate ){
           system.debug('hello buddy');
           demohandler.validationdemo(trigger.old);
       }
    }
    

    CLASS HANDLER

    public class demohandler {
        public static void validationdemo(List acc){
            Set idSet = new Set();
            for(Account acc1: acc){
                idSet.add(acc1.id);
            }
    
            List accList = [Select id, Area__c,(select id, Title__c from Designations__r) from Account where Id IN: idSet];
            for(Account act:Designation__c.){
                for(Designation__c deg:accList.act){  
                    if(deg.Title__c == 'CEO' && act.Area__c == ''){
                        act.addError('Area should not be blank');
                    }
                }
            }
        }
    }
    
  11. trigger on contentversion object which inserts contentdocumentlink to share files specific user whenever a new file is uploaded.
  12. Code

    eed to put a check to verify if ContentDocumentLink records exist before putting it into final list ContentDocumentList. Logic will be like this.
    
    trigger ContentVersionTrigger on ContentVersion (after insert) {
        if(!TriggerRunOnce.hasAlreadyfired())
        {
            List users = [select user.id, user.Email, user.FirstName, user.LastName, user.profile.name, user.Username, user.IsActive 
            FROM user, user.profile 
            where user.LastName IN ('***','***') and user.IsActive=true];
            Set contentDocumentIdSet = new Set();
    
            for(ContentVersion cv:trigger.new)
            {
                if(cv.ContentDocumentId != null)
                {
                    contentDocumentIdSet.add(cv.ContentDocumentId);
                }
            }
    
            List lstContentDocumentlink = [SELECT ContentDocumentId, LINKEDENTITYID 
                                                                FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet];
    
    
            List ContentDocumentList = new List();
    
    
            for(ContentVersion cv:trigger.new)
            {
                system.debug('at 5 '+cv);
                if(cv.ContentDocumentId != null && !lstContentDocumentlink.contains(cv.ContentDocumentId))
                {
                    for(user u:users){
                        if(u.Id != cv.OwnerId){
                            ContentDocumentLink cdl = new ContentDocumentLink(ContentDocumentId=cv.ContentDocumentId,LINKEDENTITYID = u.Id,SHARETYPE='C');
                            ContentDocumentList.add(cdl);  
                        }
                    }
                }
            }
    
            insert ContentDocumentList;
            TriggerRunOnce.setAlreadyfired();
        }
    }      
    
  13. Trigger on contentversion object which inserts contentdocumentlink to share files specific user whenever a new file is uploaded.
  14. Code

    
    
    trigger ContentVersionTrigger on ContentVersion (after insert) {
        if(!TriggerRunOnce.hasAlreadyfired())
        {
            List users = [select user.id, user.Email, user.FirstName, user.LastName, user.profile.name, user.Username, user.IsActive 
            FROM user, user.profile 
            where user.LastName IN ('***','***') and user.IsActive=true];
            Set contentDocumentIdSet = new Set();
    
            for(ContentVersion cv:trigger.new)
            {
                if(cv.ContentDocumentId != null)
                {
                    contentDocumentIdSet.add(cv.ContentDocumentId);
                }
            }
    
            List lstContentDocumentlink = [SELECT ContentDocumentId, LINKEDENTITYID 
                                                                FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet];
    
    
            List ContentDocumentList = new List();
    
    
            for(ContentVersion cv:trigger.new)
            {
                system.debug('at 5 '+cv);
                if(cv.ContentDocumentId != null && !lstContentDocumentlink.contains(cv.ContentDocumentId))
                {
                    for(user u:users){
                        if(u.Id != cv.OwnerId){
                            ContentDocumentLink cdl = new ContentDocumentLink(ContentDocumentId=cv.ContentDocumentId,LINKEDENTITYID = 																				u.Id,SHARETYPE='C');
                            ContentDocumentList.add(cdl);  
                        }
                    }
                }
            }
    
            insert ContentDocumentList;
            TriggerRunOnce.setAlreadyfired();
        }
    }
    
  15. Write a trigger automatically create the Pricebook entry for each Product record inserted.
  16. Code

    
    trigger createPriceBookEntry on Product2 (after insert) {
        
        List priceBookEntryList= new List();
        
        String pricebkId= [SELECT id from Pricebook2 where isStandard=true][0].Id;
        
        for(Product2 prod: trigger.new){
            
            priceBookEntry priceBkEntry= new priceBookEntry();
            priceBkEntry.Product2Id= prod.Id;
            priceBkEntry.Pricebook2Id= pricebkId;
            priceBkEntry.IsActive= True;
            priceBkEntry.UnitPrice= 100; // Dummy Value
            priceBkEntry.UseStandardPrice= False;
            //Add more fields as per requirement
            
            priceBookEntryList.add(priceBkEntry);
        }
        
        if(priceBookEntryList.size()>0){
            insert priceBookEntryList;
        }
    }
    

No comments:

Post a Comment