4

I have a trigger on the OpportunityLineItem acting after delete. From that trigger, I want to query all the Opportunities associated to the OpportunityLineItems deleted to see if they still have other OpportunityLineItems associated to them.

The Opportunity SObject has to field that should help me with that:

  • HasOpportunityLineItem
  • TotalOpportunityQuantity

The problem is that the value of this field doesn't seem to be accurate when I query it after the action.

Am I missing something? If not, what is an efficient way of achieving this?

1

"Formula" style fields, such as HasOpportunityLineItem and TotalOpportunityQuantity, are not set until after all triggers have executed. They are updated in the same phase as normal rollup summary fields. See the Triggers and Order of Execution for more information on the specific order of operations. You'll need to run a query to find out what's left.

Set<Id> oppIds = new Set<Id>(), remainIds = new Set<Id>();
for(OpportunityLineItem record: Trigger.old) {
    oppIds.add(record.OpportunityId);
}
for(AggregateResult result: [SELECT Count(Id) Sum, OpportunityId oppId FROM OpportunityLineItem WHERE OpportunityId in :oppIds GROUP BY OpportunityId]) {
    remainIds.add((Id)result.get('oppId'));
}
// remainIds now contains all records that have at least one other item still

There are other means of reaching this conclusion, but this would be one straight-forward way of determining which opportunities still have line items.

0

AggregateResult ar = [Select Count(ID) From OpportunityLineItem where OpportunityID = :oppID];

1
  • 1
    Eric -- I think you should modify this answer to be bulkified as it will execute within the OLI trigger – cropredy Oct 6 '14 at 16:47

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.