Here's an example of a trigger that can help you accomplish this:
Copy code :
trigger UpdateOpportunityFields on OpportunityLineItem (after insert, after update) {
// Map to store OpportunityIds and the sum of Custom_Prod_Field_1__c and Custom_Prod_Field_2__c for each Opportunity
Map<Id, OpportunityFields> oppFieldsMap = new Map<Id, OpportunityFields>();
// Iterate through the OpportunityLineItems and store the sum of Custom_Prod_Field_1__c and Custom_Prod_Field_2__c for each Opportunity
for (OpportunityLineItem oppLineItem : Trigger.new) {
// Check if the OpportunityId is not already in the map
if (!oppFieldsMap.containsKey(oppLineItem.OpportunityId)) {
// Create a new OpportunityFields object and add it to the map
OpportunityFields oppFields = new OpportunityFields();
oppFields.OpportunityId = oppLineItem.OpportunityId;
oppFields.Custom_Opp_Field_1__c = oppLineItem.Custom_Prod_Field_1__c;
oppFields.Custom_Opp_Field_2__c = oppLineItem.Custom_Prod_Field_2__c;
oppFieldsMap.put(oppLineItem.OpportunityId, oppFields);
} else {
// If the OpportunityId is already in the map, update the sum of Custom_Prod_Field_1__c and Custom_Prod_Field_2__c
OpportunityFields oppFields = oppFieldsMap.get(oppLineItem.OpportunityId);
oppFields.Custom_Opp_Field_1__c += oppLineItem.Custom_Prod_Field_1__c;
oppFields.Custom_Opp_Field_2__c += oppLineItem.Custom_Prod_Field_2__c;
}
}
// Create a list to store the updated Opportunities
List<Opportunity> oppsToUpdate = new List<Opportunity>();
// Iterate through the map and update the Opportunity fields
for (OpportunityFields oppFields : oppFieldsMap.values()) {
Opportunity opp = new Opportunity();
opp.Id = oppFields.OpportunityId;
opp.Custom_Opp_Field_1__c = oppFields.Custom_Opp_Field_1__c;
opp.Custom_Opp_Field_2__c = oppFields.Custom_Opp_Field_2__c;
oppsToUpdate.add(opp);
}
// Update the Opportunities
if (!oppsToUpdate.isEmpty()) {
update oppsToUpdate;
}
}
// OpportunityFields class to store the OpportunityId and the sum of Custom_Prod_Field_1__c and Custom_Prod_Field_2__c for each Opportunity
public class OpportunityFields {
public Id OpportunityId { get; set; }
public decimal Custom_Opp_Field_1__c { get; set; }
public decimal Custom_Opp_Field_2__c { get; set; }
}
This trigger listens to the `
3 respostas