[SalesForce] Trigger, count related records

Here is the case I am working with now:

There is a Custom_Object__c linked to Case object via lookup field (Custom_Object__c is a parent). After a new case is created, Case_Count__c field should be updated on Custom_Object__c with the number of cases tied to that object. Here is the sample code I wrote that adds +1 on Case_Count__c field every time a new case is inserted(works fine):

trigger CaseCount on Case (after insert) {
List<Case> lstCase = [select id, Custom_object_lookup__c, Type from Case where id in: trigger.newmap.keyset()];
set<Id> custObjId = new set<Id>(); 
for(Case cs: lstCase){
    if(cs.Custom_object_lookup__c != null) {
        custObjId.add(cs.Custom_object_lookup__c);   

    }

    if(custObjId != null && custObjId.size() > 0) { 

    List<Custom_object__c> lstCustomObject= [select id, Case_Count__c from Custom_object__c where id in: custObjId ]; 


    if(lstCustomObject.size() > 0){
        for(Custom_object__c custObj: lstCustomObject){
            System.debug('Case count before update: ' + custObj.Case_Count__c);
            custObj.Case_Count__c += 1;
            System.debug('Case count after update: ' + custObj.Case_Count__c);

        }
        }

      update lstCustomObject;

    }

}}

Question: What would be correct way/approach to query all the cases related to Custom_object__c and update the Case_count__c field accordingly?

Best Answer

Rather than coding your own solution, I'd recommend using DLRS to do the work for you. It is a free tool and very powerful. It will let you rollup counts as part of inserts, and also run rollups on a schedule or adhoc. It will also solve some problems that you haven't addressed in your code such as deletes of cases or changes to the custom object lookup field.

If you want to write your own code, you can use an aggregate query to get a count of cases this way:

SELECT Custom_object_lookup__c, Count(Id) 
FROM Case 
GROUP BY Custom_object_lookup__c
Related Topic