Rollup Sumary in lookup relationship using triggers salesforce

Trigger Code :

trigger parentChildCount_Trg on Contact(after insert, after update, after delete, after undelete) {
    Map < Id, Account > conMapId = new Map < Id, Account > ();
    Set < Id > conSetIds = new Set < Id > ();
    for (Contact con: ((trigger.isAfter) && (trigger.isInsert || trigger.isUndelete || trigger.isUpdate)) ? trigger.new : trigger.old) {
        if (String.isNotBlank(con.AccountId)) {
            conSetIds.add(con.AccountId);
        }
    }
    conSetIds.remove(null);
    if (!conSetIds.isEmpty()) {
        for (Id acctId: conSetIds) {
            conMapId.put(acctId, new Account(Id = acctId));
        }
        for (AggregateResult aggr: [select AccountId Id, COUNT(Id) contactCount, SUM(Salary__c) salarySum, AVG(Salary__c) salaryAverage, MAX(Salary__c) salaryMax, MIN(Salary__c) salaryMin from Contact where AccountId =: conSetIds GROUP BY AccountId]) {
            conMapId.get((Id) aggr.get('Id')).Contact_Count__c      = (Decimal) aggr.get('contactCount') > 0  ? (Decimal) aggr.get('contactCount')   : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Sum_Salary__c = (Decimal) aggr.get('salarySum') > 0     ? (Decimal) aggr.get('salarySum')      : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Avg_Salary__c = (Decimal) aggr.get('salaryAverage') > 0 ? (Decimal) aggr.get('salaryAverage')  : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Max_Salary__c = (Decimal) aggr.get('salaryMax') > 0     ? (Decimal) aggr.get('salaryMax')      : 0;
            conMapId.get((Id) aggr.get('Id')).Contact_Salary_Min__c = (Decimal) aggr.get('salaryMin') > 0     ? (Decimal) aggr.get('salaryMin')      : 0;
        }
        update conMapId.values();
    }

}

No comments:

Featured

What is Cryptography in salesforce and what are all the algorithms provided by them ?

A). It is a security protocal between two systems. Lets say we are integration two systems without any encrytion mechanism then hackers wil...

Popular