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
bzain9bzain9 

Apex Trigger - Estimated Amount Roll Up (No Quote)

How would I create an apex trigger - Estimated Amount Roll Up (No Quote)? Sample code would be great!
Best Answer chosen by bzain9
Amit Singh 1Amit Singh 1
Hi,

I had created a trigger before for the rollup summary of Opportunity Product into Opportunity. I know we can achieve through rollup summary field the requirement was not to use rollup summary. 

Below is my code.
trigger OpportunityLineItemRollUpAmount_Trigger on OpportunityLineItem (After Insert, After Delete, After Undelete) {
    Map<Id, Decimal> OpportunityMap = new Map<Id, Decimal>();
    Set<Id> OpportunityIdSet = new Set<Id>();
    List<Opportunity> OpportunityToUpdateList = new List<Opportunity>();
    If(Trigger.IsInsert || Trigger.IsUndelete){
        FOR(OpportunityLineItem oppLineItem : Trigger.New){
            If(oppLineItem.OpportunityId!=null){
               OpportunityIdSet.add(oppLineItem.OpportunityId); 
            }
        }
      }
    If(Trigger.IsDelete){
        FOR(OpportunityLineItem oppLineItem : Trigger.Old){
            If(oppLineItem.OpportunityId!=null){
               OpportunityIdSet.add(oppLineItem.OpportunityId); 
            }
        }
    }
    For(AggregateResult ar : [Select Opportunityid, Sum(TotalPrice) Amount From OpportunityLineItem 
                                Where OpportunityId in : OpportunityIdSet group by OpportunityId]){
        Decimal Amount = (Decimal)ar.get('Amount');
        OpportunityMap.put((Id)ar.get('OpportunityId'), Amount);
    }
    For(Opportunity opp : [Select Id, Name, Total_Line_Item__c From Opportunity Where Id in: OpportunityIdSet]){
        opp.Total_Line_Item__c = OpportunityMap.get(opp.Id);
        OpportunityToUpdateList.add(opp);
    }
    try{
        update OpportunityToUpdateList;
    }catch(System.Exception e){
        
    }

}

Hope this will help :)
Thanks,
Amit Singh