I have a custom object O__c it has Lookup relationship to Opportunity. This Custom Object record will create when oppty stage is moved from 95% to 100% according to our requirement.

Now my question is I have 300 Opportunities already existing which has O__c Object record Each.

There is a custom field in my custom object and every time when I add new record it should validate me such a way that the recent record's custom field should be equal to it's earlier records. How can I do that?

  • Do you mean "update" not "validate"?
    – Keith C
    Commented Dec 3, 2017 at 11:21
  • What do you mean by validate? Please explain in detail with an example. Commented Dec 4, 2017 at 1:46

1 Answer 1


You can do SOQL in a trigger, so just query each of your parent opportunity's child records and compare:

Set<ID> parentOpps = new Set<ID>();
for(O__c o : Trigger.New)

Map<ID, Opportunity> opps = new Map<ID, Opportunity>(
     [select ID, (select ID, Custom_Field__C from Os__r) from Opportunity
      where ID in :parentOpps]

for(O__c newO : Trigger.New)
    for(O__c existingO : opps.get(newO.Opportunity__c).Os__r)
        if(existingO.Custom_Field__c != newO.Custom_Field__c)
            newO.addError('Custom Field does not match');

Also, something this doesn't consider is the case of two or more O__c records being inserted at once to an Opportunity with no child records.

  • In theory you could add LIMIT 1 to your Left Outer Join, so that your inner for loop wouldn't have to do so much work. Ostensibly this trigger would have fired against each other child also, so one is as good as all.
    – Adrian Larson
    Commented Dec 3, 2017 at 14:41
  • @AdrianLarson I considered that, but I've been bitten by assuming data is always saved in a good state before. Commented Dec 3, 2017 at 23:36

You must log in to answer this question.

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