How to access old value and new value in before update trigger

  • I have implement a before update trigger. I want to fetch the old value which was there and new value which i just entered to update.

    I have used trigger.newMap.keyset() and trigger.oldMap.keyset(), but I am getting same data in both i.e old value.

    Here is my code:

    if (Trigger.isUpdate && Trigger.isBefore) {
        List<CountParent__c> incCount;
        Set<id> triggerIds = Trigger.oldMap.keySet();
        List<CountChild__c> fetchChild = [select Name, CountParent__r.name from CountChild__c where Id IN: triggerIds];
        system.debug('old====' + fetchChild);
        Set<id> triggerIds1 = Trigger.newMap.keySet();
        List<CountChild__c> fetchChild1 = [select Name, CountParent__r.name from CountChild__c where Id IN: triggerIds1];
        system.debug('new====' + fetchChild1);
        List<CountParent__c> fetchParent = [select Name, NoOfChildRecords__c from CountParent__c];
        for (CountChild__c a: fetchChild1) {
            for (CountParent__c b: fetchParent) {
                if (b.Name == a.CountParent__r.Name) {
                    incCount = new List < CountParent__c > ();
                    b.NoOfChildRecords__c = b.NoOfChildRecords__c + 1;
                    incCount.add(b);
                }
            }
        }
        update incCount;
    }
    
  • MSCB

    MSCB Correct answer

    5 years ago

    Hai cooolranjan try this new code snippet.

    trigger updateCount on CountChild__c(After Insert, After Update) {
    
        if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate)) {
    
            Set<Id> parentIds = new Set<Id>();    // intialize set of Id stores parentId
            List<CountParent__c> parentListForUpdate = new List<CountParent__c>();  // Initialize Parent Record List
            Map<Id,Integer> parentIdAndChildCountMap = new Map<Id,Integer>();   // initialize parentId and child count Map
    
            for(CountChild__c child : trigger.new) {  // Trigger.new records
                if(child.CountParent__c != null) { 
    
                    if(trigger.isInsert) {    // If trigger is insert directly add parent Id in a set
                        parentIds.add(child.CountParent__c);    
                    }
    
                    // If trigger is update check parent Id change or not then add parent Id in a set
                    if(trigger.isUpdate && trigger.oldMap.get(child.Id).CountParent__c != child.CountParent__c) {    
    
                        parentIds.add(child.CountParent__c);    // new parent Id
    
                        if(trigger.oldMap.get(child.Id).CountParent__c != null) {
                            parentIds.add(trigger.oldMap.get(child.Id).CountParent__c);    // old parent Id
                        }
                    }
                }
            }
    
            if(parentIds.size() > 0) {    
                //Query the new and old parent child records and added the count into the map
                for(CountChild__c child : [SELECT Id,Name,CountParent__c FROM CountChild__c WHERE CountParent__c IN :parentIds]) {
    
                    if(!parentIdAndChildCountMap.containsKey(child.CountParent__c)) 
                        parentIdAndChildCountMap.put(child.CountParent__c, 0);    // Initialize the count set to '0'
    
                    parentIdAndChildCountMap.put(child.CountParent__c, parentIdAndChildCountMap.get(child.CountParent__c)+1);
                }
            }
    
            if(parentIdAndChildCountMap.size() > 0) {
                for(Id parentId : parentIds) {    // parentid  looping
    
                    CountParent__c parent = new CountParent__c();    //intialize new parent Instance
                    parent.Id = parentId;
                    if(parentIdAndChildCountMap.containsKey(parentId)) {
                        parent.NoOfChildRecords__c = parentIdAndChildCountMap.get(parentId);    //get count put to the NoOfChildRecords__c field value
                    } else {
                        parent.NoOfChildRecords__c = 0;    // if the parentId doesn't contais map to put 0
                    }
                    parentListForUpdate.add(parent);    //Added parent list
                }
            }
    
            if(parentListForUpdate.size() > 0) {
                update parentListForUpdate;    // Update the parent List
            }
        }
    }
    

    almost working as desired. thank you so much @MSCB

    your welcome @Cooolranjan

    [email protected] , counter is stuck at 1. it needs to zero if no record is associated to that particular parent.

    Check my updated code and verify. @Cooolranjan

    Still it's showing 1 since it should shown 0.

    When this works wrong Insert or update operation?

    update suppose i have two parent records and 4 child records, initially both parent records have 2-2 child records. then i updated the parent lookup in child records. now i have p1 with 4 and p2 with 0. but p2 still showing NoOfChildRecords__c = 1

    Its work fine in my dev org. please check your code logic.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used