1

I'm still very much new to Apex so I was hoping to get some feedback on a trigger I wrote. The requirement is upon an opportunity reaching stage 5, query the account team of the related Account and find the relationship and technical account manager and write that to the opportunity.

The code works but I'm wondering if I should only use one query. What can I do to optimize this? Thanks in advance

trigger Opportunity_SetAcccountTeamOnClose on Opportunity (before update) {

set<ID> AccountIDs = new set<ID>();
map<ID,AccountTeamMember> RMTeamMap=new Map<ID,AccountTeamMember>();
map<ID,AccountTeamMember> TAMTeamMap=new Map<ID,AccountTeamMember>();

for(Opportunity o : Trigger.new){
    if(o.StageName == 'Stage 5'){
      AccountIDs.add(o.accountid);
  }
}

for(AccountTeamMember rmatm : [Select a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId 
                            From AccountTeamMember a 
                            where a.TeamMemberRole='Relationship Manager' AND a.AccountId in :AccountIDs]){
    RMTeamMap.put(rmatm.Accountid,rmatm);
}

for(AccountTeamMember tamatm : [Select a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId 
                            From AccountTeamMember a 
                            where a.TeamMemberRole='Technical Account Manager' AND a.AccountId in :AccountIDs]){
    TAMTeamMap.put(tamatm.Accountid,tamatm);
}

for(Opportunity o : Trigger.new){
    if(o.StageName == 'Stage 5'){
        if(RMTeamMap.containsKey(o.AccountId)){
            o.Relationship_Manager__c=RMTeamMap.get(o.AccountId).User.Name;
        if(TAMTeamMap.containsKey(o.AccountId)){
            o.Technical_Account_Manager__c=TAMTeamMap.get(o.AccountId).User.Name; 
            }
        }
    }
} 

}

2

From a governor limit perspective, I would say that, yes, you should consider collapsing your queries into a single query:

for(AccountTeamMember rmatm : [Select a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId 
                            From AccountTeamMember a 
                            where a.TeamMemberRole IN ('Relationship Manager','Technical Account Manager') AND a.AccountId in :AccountIDs]){
    if(rmatm.teammemberrole == 'Relationship Manager') {
        RMTeamMap.put(rmatm.Accountid,rmatm);
    }
    if(rmatm.teammemberrole == 'Technical Account Manager') {
        TAMTeamMap.put(tamatm.Accountid,tamatm);
    }
}

You could also avoid the query if there are no accounts to query from.

if(accountIds.isEmpty()) {
    return;
}
| improve this answer | |

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.