Roll Up Opportunity Amount on an Account Field

Roll Up Opportunity Amount on an Account Field:


Lets say we want to rollup Opportunity amount on Account field named totalOpptyAmount__c -


 trigger rollUpOpportunity on Opportunity (after delete,after update,after insert,after undelete) {

    set<ID>accIds = new set<ID>();   

    if(trigger.isinsert || trigger.isundelete){

        for(Opportunity oppty : trigger.new){

            accIds.add(oppty.AccountId);

        }

    }

    if(trigger.isdelete){

        for(Opportunity oppty : trigger.old){

            accIds.add(oppty.AccountId);           

        }        

    }

    if(trigger.isupdate){

        for(Opportunity oppty:trigger.new){

            accIds.add(oppty.AccountId);

            if(trigger.oldmap.get(oppty.id).AccountId != oppty.AccountId && trigger.oldmap.get(oppty.id).AccountId != null ){

                accIds.add(trigger.oldmap.get(oppty.id).AccountId);

            }            

        }

    }    

    Map<id,double> amountMap = new Map<id,double>();

    for(aggregateresult ag : [select AccountId ,SUM(Amount) sA from Opportunity where AccountId in:accIds group by AccountId]){

        amountMap.put((ID)ag.get('AccountId'), double.valueof(ag.get('sA')));

    }

    list<Account>acclist = new list<Account>();

    for(id aId : accIds){

        Account acct = new Account(id=aId);

        if(amountMap.containskey(aId)){

            acct.totalOpptyAmount__c = amountMap.get(aId);

        }else{

            acct.totalOpptyAmount__c = 0;

        } 

        acclist.add(acct);       

    }

    if(acclist.size()>0){

        update acclist;

    }

}

Comments