Skip to main content
Hi everyone,

I've got two custom fields in the Opportunities Object (Custom_Opp_Field_1__c, Custom_Opp_Field_2__c) that need to be updated with information from a two fields in Opportunity Product Object (Custom_Prod_Field_1__c, Custom_Prod_Field_2__c) whenever a new Opportunity Product is added or edited.

I've never written a Trigger before, so any help is very much appreciated!

Thanks in advance!

Best,

Ryno Lourens

 
3 respostas
  1. 5 de fev. de 2023, 23:10

    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 `

     
0/9000