-2

Hi i am new to triggers need some help to start the following.

Products is a related object on opportunity and it can have multiple records. I need a trigger to summarize (Product Name, Quantity, Sale Price, Total Price) and put that on the opportunity as a text field.

1
  • 1
    Your first port of call when trying to learn about a part or feature of Salesforce that you're not familiar with should be trailhead.salesforce.com . And as always, you should show us what you've tried (so that your question doesn't look like a "do my work for me" request) and be as specific as possible about where you're stuck.
    – Derek F
    Nov 30, 2023 at 1:14

1 Answer 1

1

This is as simple as querying the records and updating the field.

trigger summarizeProducts on Opportunity(before update) {
  // Reset field
  for (Opportunity record : Trigger.new) {
    record.SummaryField__c = '';
  }
  // Query each line item
  for (OpportunityLineItem record : [
    SELECT OpportunityId, Product2.Name, Quantity, UnitPrice, TotalPrice
    FROM OpportunityLineItem
    WHERE OpportunityId = :Trigger.new
  ]) {
    // And add it to the summary field
    Trigger.newMap.get(record.OpportunityId).SummaryField__c +=
      String.join(
        new List<Object>{
          record.Product2.Name,
          record.Quantity,
          record.UnitPrice,
          record.TotalPrice
        },
        ','
      ) + '\n';
  }
}

This should be sufficient to get started.

1
  • N.B. to Rajdeep -- always worth checking the concatenated string size against the target field's length and truncating as otherwise you'll get an exception. Might not be an issue for you if not too many products per Opportunity
    – cropredy
    Nov 30, 2023 at 1:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .