+ Start a Discussion
DeptonDepton 

trigger to get the total number of close cases per contact

Hi all,

 

 

I cannot create a Roll-Up Summaryfield on Contats to see the total of close cases in the contact detail page.

 

Any sample code for this?

 

Tank you

Gunners_23Gunners_23

Please find the below link for sample code regarding creating the custom roll-up summary 

 

http://www.anthonyvictorio.com/salesforce/roll-up-summary-trigger/

DeptonDepton
/* Provide summary of Number of Cases on Contact record */

trigger CasestSumTrigger on Case (after delete, after insert, after undelete,
after update) {

    Case[] cas;
    if (Trigger.isDelete)
        cas = Trigger.old;
    else
        cas = Trigger.new;

    // get list of Contacts 
    Set<ID> contIds= new Set<ID>();
    for (Case cs : cas) {
            contIds.add(cs.ContactId);
    }
   
    Map<ID, Case> CasesForContact = new Map<ID, Case>([select Id
                                                            ,ContactId
                                                            from Case
                                                            where ContactId in :contIds]);

    Map<ID, Contact> contToUpdate= new Map<ID, Contact>([select Id
                                                                 ,items__c
                                                                  from Contact
                                                                  where Id in :contIds]);
                                                               
    for (Contact cont: contToUpdate.values()) {
        Set<ID> csIds = new Set<ID>();
        for (Case cs : CasesForContact.values()) {
            if (cs.ContactId == cont.Id)
                csIds.add(cas.Id);
        }
        if (cont.Number_of_Cases__c != csIds .size())
            cont.Number_of_Cases__c =  csIds .size();
    }

    update contToUpdate.values();
}

 I managed to create this but still got an error:

Error: Compile Error: Initial term of field expression must be a concrete SObject: LIST<Case> at line 32 column 27

 

Thanks!

 

Gunners_23Gunners_23

Error is because of this csIds.add(cas.Id);    // Cas is an array

csIds.add(cas.Id);