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

Update Opportunity from LineItem trigger

I am working on a trigger that will sum some of the values from the opportunityLineItems and update a field on the opportunity. These are custom fields that do not automatically sum and our org has already used 100% of available roll-up summary fields and there are existing integration pieces that rely on these fields. 


Currently they are updated via s-control that has to be manually envoked from a link on each record. 


I have some experience with Apex Trigger, but am hoping somebody may be able to help me get started... 


So far I have:

trigger Calculate_Products on OpportunityLineItem (after delete, after insert, after undelete, 
after update) {

	//Set the OpportunityID
	Set<id> Ids = new Set<id>();
     for (OpportunityLineItem oli : {
	//Query the OpportunityLineItems
	List<aggregateResult> results = [select sum(margin__c)m from opportunityLineItem where OpportunityId in :Ids];
    for (OpportunityLineItem oli : 
   	Opportunity Opp = opptys.get(oli.OpportunityId);
    Opp.Margin_Total__c = results.get('m');
	update opp;


 but I am not quite sure how to I can sum the margin__c field and update the opportunity total_margin__c field... or how to ensure the trigger is bulk friendly. 


Thanks in advance for any help! 



Aslam ChaudharyAslam Chaudhary
First of all, Your code is not seems correct to me. You created opportunity object wihtin for loop.  Please use List<Opportunity > and Add opp in List of Oppotunity. Update list object. Also I hope you need to use the group by clause for OpportunityID. Let me know if this clarifies else I will paste the code to do the same.