1

I need to access the value from a roll-up field on my Opportunities, from it's related Opportunity Product.

When I use oli.Opportunity.Software_Line_Item__c the value retrieved is always null.

So I've also tried oli.OpportunityId.Software_Line_Item__c which causes an error in the compiler

Invalid foreign key relationship: OpportunityLineItem.OpportunityId

& just to make sure that it's not the roll-up field calculation that's not working as expected, I've tested oli.Opportunity.Name which is also returning null.

I know this is basic but I don't have Eclipse installed so I can't check the correct reference to use. Could someone please let me know how I can navigate this relationship, to retrieve the value from the Software_Line_Item__c field?

2

You don't get related values "for free" in a trigger, you have to query them first:

trigger X on OpportunityLineItem (after insert, after update) {
     Map<Id, OpportunityLineItem> lineItems = new Map<Id, OpportunityLineItem>([SELECT Opportunity.Software_Line_Item__c FROM OpportunityLineItem WHERE Id IN :Trigger.new]);
     for(OpportunityLineItem record: Trigger.new) {
         Opportunity opp = lineItems.get(record.Id).Opportunity;
         // opp.Software_Line_Item__c has the value you want
     }
}

Alternatively, of course, you can use the usual Aggregate-Query-Update pattern:

trigger ...
    Map<Id, Opportunity> opps = new Map<Id, Opportunity>();
    for(OpportunityLineItem record: Trigger.new) {
        opps.put(record.OpportunityId, null);
    }
    opps.putAll([SELECT Software_Line_Item__c FROM Opportunity WHERE Id IN :opps.keySet()]);
    for(OpportunityLineItem record: Trigger.new) {
        Opportunity opp = opps.get(record.OpportunityId);
        // opp.Software_Line_Item__c has the value you want
    }
}

Also remember that you might need to do work asynchronously, because the rollup summary value will be incorrect until nearly the last phase of the transaction, long after the after commit trigger events have fired.

  • Ha! Not even one field?? Thanks, not the answer I was hoping for but at least I know now. – Alex S Jul 15 '15 at 22:39
  • Frustrating, indeed. Curiously, you'll also note that Trigger.new[0].Opportunity is null, but Trigger.new[0].Opportunity.Name doesn't give a NullPointerException. Just a little bit of Salesforce magic. – sfdcfox Jul 15 '15 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.