function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
devloper sfdcdevloper sfdc 

Rollup summery on case object

Hi All,

I nedd Rollup summery on Case object using trigger . pleae help me.
Best Answer chosen by devloper sfdc
<Saket><Saket>
Hi DeveloperSfdc

Please try the code below, if you face any problem then let me know
 
trigger RollUpCase on Case (after insert, after update, after delete, after undelete) {
    
    List<Case> allCase = Trigger.IsDelete ? trigger.old : Trigger.new;
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    
    for(Case ca : allCase)
    {
        	
        if(ca.ContactId != null)
            conMap.put(ca.ContactId, new Contact(Id= ca.contactId, Count_Of_Case__c=0));
    }
    
    for(AggregateResult ar : [select count(Id) cou,ContactId from Case where ContactId in : conMap.keySet() Group By ContactId])
    {
        Id conid = Id.valueOf(ar.get('ContactId')+'');
        Contact con = conMap.get(conId);
        con.Count_of_Case__c = Integer.valueOf(ar.get('cou'));
    }
    
    if(conMap.values() != null && conMap.values().size() > 0)
        update conMap.values();
        
}

 

All Answers

bretondevbretondev
You can set up a Roll-up summary field without a trigger.
What is your use case?
devloper sfdcdevloper sfdc
I want to update total count case on contact object
<Saket><Saket>
Hi DeveloperSfdc

Please try the code below, if you face any problem then let me know
 
trigger RollUpCase on Case (after insert, after update, after delete, after undelete) {
    
    List<Case> allCase = Trigger.IsDelete ? trigger.old : Trigger.new;
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    
    for(Case ca : allCase)
    {
        	
        if(ca.ContactId != null)
            conMap.put(ca.ContactId, new Contact(Id= ca.contactId, Count_Of_Case__c=0));
    }
    
    for(AggregateResult ar : [select count(Id) cou,ContactId from Case where ContactId in : conMap.keySet() Group By ContactId])
    {
        Id conid = Id.valueOf(ar.get('ContactId')+'');
        Contact con = conMap.get(conId);
        con.Count_of_Case__c = Integer.valueOf(ar.get('cou'));
    }
    
    if(conMap.values() != null && conMap.values().size() > 0)
        update conMap.values();
        
}

 
This was selected as the best answer
devloper sfdcdevloper sfdc
Thanks  saket it is work please help to create test class for this trigger