0

Simple question probably. Imagine a use case where, I need to have the highest amount value from all associated Opportunity rolled up onto a field on the Account.

I am aware about the bulkification practice. Where you include a for loop, that iterates through trigger.new. But how would I do this? Logically, I imagine:

  1. Trigger on opportunity
  2. For loop starts...
  3. Inside For loop, I have to look for all associated opportunities for the current opportunity's account (but that is SOQL inside FOR loop).

I know that is bad. So, what is the practice in handling such situations?

Ignore the possibility of using Roll Up Summary. This is not the exact use case. But it reflects the need I have in authoring code.

1
  • Where is the part in your example about a grandchild as mentioned in your title?
    – Eric
    Nov 22 '16 at 12:46
1

Create a map of Account with List of Opportunities Map<Id, List<Opportunity> and based on the Map in the for loop just iterate the List and code as per your business logic.

sample e.g. Below code is not compiled its just an example

Map<Id,List<Opportunity> accIdOppListMap = new Map<Id,List<Opportunity>();
Set<Id> accountIdSet = new Set<Id>();
for(Opportunity oopObj: Trigger.new){
    accountIdSet.add(oopObj.AccountId);
}
for(Opportunity oopObj: [Select AccountId from Opportunity Where AccountId IN: accountIdSet]) {
    if(!accIdOppListMap.containsKey(oopObj.AccountId)){
        accIdOppListMap.put(oopObj.AccountId, new List<Opportunity>{oopObj});
    } else {
        accIdOppListMap.get(oopObj.AccountId).add(oopObj);
    }
}

//2nd for loop where your want to get all the related Opportunity List of current Opp Account get from the Map and you got the whole list and based on the List of Opp do further processing.

for(Opportunity oopObj: Trigger.new) {
    List<Opportunity> tempOppList = accIdOppListMap.get(oopObj.AccountId);

    //Do further processing on the tempOppList
}
0

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.