+ Start a Discussion

Simulate Max Roll-up Summary


I am trying to simulate the MAX function on the roll-up summary fields with the trigger below but I am getting an error that my aggregate variable on line 18 is not recognized.  Can any suggest how I can fix this to write the Maximum value of the custom field Max_Deliv__c on my OpportunityLineItem object to the related Opportunity object field Max_Deliv__c?  Thanks,

trigger UpdateMaxDeliv on OpportunityLineItem(before update) {

Set <Id> Opp_Ids = new Set<Id>();
	for (OpportunityLineItem oli1: trigger.new){

List<AggregateResult> maxDeliv = [SELECT Max(Max_Deliv__c) deliv
								  FROM OpportunityLineItem];
	for(AggregateResult aggOli : maxDeliv);{
		List<Opportunity> opp1 = [SELECT Id, Max_Deliv__c
								  FROM Opportunity
								  WHERE Id in :Opp_Ids];

			for(Opportunity o: opp1){
				o.Max_Deliv__c = aggOli.get('deliv');
			update opp1;

I would write the code like below:
trigger UpdateMaxDeliv on OpportunityLineItem(before update) {

for(Opportunity opp : [SELECT Id,(Select Max_Deliv__c from OpportunityLineItems Order by Max_Deliv__c DESC LIMIT 1), FROM Opportunity where Id in : trigger.newMap.keyset()])
       Opp.Max_Deliv__c  = Opp.OpportunityLineItems[0].Max_Deliv__c;
No need to perform "Update" DML again since it is BEFORE Update event.