Tuesday, June 19, 2018

Rollup summary trigger for sum in salesforce

Trigger contactSumTrigger on Contact(After insert,After Delete,After Undelete,After update)
{
    Set<Id> setAccountIds = new Set<Id>();   
   
    if(Trigger.isInsert || Trigger.isUndelete || Trigger.isupdate)
    {
        for(Contact con : Trigger.new)
        {
            setAccountIds.add(con.AccountId);
        }
    }
   
    if(Trigger.isDelete)
    {
       
        for(Contact con : Trigger.old)
        {
            setAccountIds.add(con.AccountId);
        }
    }
    set<Account> lstAcc = new set<Account>();
    System.debug(setAccountIds);
    List<AggregateResult> lstCon = [select accountid,sum(Amount__c) am from contact where accountid in : setAccountIds group by accountid];
   
    for(AggregateResult ar : lstCon){
        for(Contact c:trigger.new){
            if(c.accountid == ar.get('accountid')){
                account a = new Account(id = c.accountid);
                a.Total_Amount__c = Decimal.valueOf(String.valueOf(ar.get('am')));
                lstAcc.add(a);
            }
        }
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.