0

I have the Opportunity object with children records called Workshare__c. There is a field on Workshare__c that is a percent (Work_Share_percent__c). We don't have any rollup fields available on the opportunity so I need to write a class that throws an error when a user tries to save a Workshare record and that record and all of its sibling's Work_Share_percent__c values are greater than 100%.

for example, I have an opportunity called 'Big Deal'. This 'Big Deal' Opportunity has 3 Workshare child records.

  • Workshare A where Work_Share_percent__c = 50%
  • Workshare B where Work_Share_percent__c = 20%
  • Workshare C where Work_Share_percent__c = 10%

If I tried to create an additional Workshare child record on 'Big Deal' Opportunity, with a workshare_percent greater than 20% the user should be blocked from saving that record unless it is 20% or less.

I hope that makes sense and thanks in advance for your help.

1
  • 1
    What have you tried? Where are you stuck? You can edit your post to add more details.
    – David Reed
    Jan 14, 2021 at 2:59

1 Answer 1

1

That's easy. Just do an AggregateResult query and you can give the appropriate error.

trigger WorkshareGreaterThan100 on Workshare__c (after insert, after update, after undelete) {
  // Get the Opportunity ID values
  Map<Id, AggregateResult> results = new Map<Id, AggregateResult>();
  for(Workshare__c record: Trigger.new) {
    results.put(record.Opportunity__c, null);
  }
  // Query for existing records
  results.putAll([
    SELECT Opportunity__c Id,
        SUM(Work_Share_percent__c) sum
    FROM Workshare__c
    WHERE Opportunity__c = :results.keySet()
    GROUP BY Opportunity__c]);
  // Prevent saving for any records that sum greater than 100%
  for(Workshare__c record: Trigger.new) {
    if(results.get(record.Opportunity__c)?.get('sum') > 100) {
      record.Work_Share_Percent__c.addError('This amount would exceed 100%. Please reduce the percent.');
    }
  }
}
0

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