1

I wrote a trigger to find the largest amount value for all Opportunities under a particular Account and then update a custom field on Account with the name of the Opportunity. It works fine with single records but as you can see it doesn't take bulk processing into account and fails because it calls too many SOQL queries.

I've tried putting the queries into maps but I generally end up with null values. If someone could point me in the right direction, I think I could figure it out, but I'm kind of stuck right now.

trigger UpdateLoanName on Opportunity (before update) {
  for (Opportunity opp : Trigger.new){
    if(opp.AccountId != null){
      Opportunity oppname = [SELECT name, amount FROM Opportunity WHERE accountid = :opp.AccountId ORDER BY amount DESC LIMIT 1];
      Account acc = [SELECT loan_name__c FROM Account WHERE id = :opp.AccountId];
      acc.loan_name__c = oppname.name;
      if(acc.loan_name__c != null){
        update acc;  
      }
    }
  }
}
2

Never write code if you can avoid it.

Instead, install Rollup Helper which is free for your first 3 rollups.

Then create a rollup helper setting

  • target field: Account.Loan_Name__c
  • source field: Opportunity.Name
  • filter
    • order by Amount DESC
    • limit 1

Then you're done

Disclaimer: I'm a member of the PassageTech partner program, I don't get referrals, although they did discount how much my company pays for it.

0

You can try below code. This is bulkified and will work fine.

     trigger UpdateLoanName on Opportunity (before update) { 
    Set<Id> accIdSet = new Set<Id>();
    Map<Id, String> mapOfAccIdAndOppName = new Map<Id, String>();
    List<Account> accListToUpdate = new List<Account>();

    for (Opportunity opp : Trigger.new){
      if(opp.AccountId != null){
        accIdSet.add(opp.AccountId); 
      }
    }

    for(Opportunity opp : [SELECT Name, Amount FROM Opportunity WHERE AccountId IN: accIdSet ORDER BY Amount DESC nulls last]){
      if(!mapOfAccIdAndOppName.containsKey(opp.AccountId) && opp.Amount != NULL){
        mapOfAccIdAndOppName.put(opp.AccountId, opp.Name);
      }
    }

    if(!mapOfAccIdAndOppName.isEmpty()){
      for(Id accId : mapOfAccIdAndOppName.keySet()){
        accListToUpdate.add(new Account(Id = accId, loan_name__c = mapOfAccIdAndOppName.get(accId)));
      }
    }
    if(!accListToUpdate.isEmpty()){
      update accListToUpdate
    }
   }

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.