Skip to main content
Hi there, 

I desperatly need help tweaking this code. It works to pull in the active opportunity on the account level, but does not work when doing mass updates/uploads. I have the understading that the querry needs to be moved outside the loop but don't know how to do that exactly.

trigger act_opp on Account (before insert, before update) {

map<Id, Account> acctmap = new map<Id, Account>();

for(Account a : trigger.new){

acctmap.putAll([SELECT Id, (SELECT Id, Name FROM Opportunities WHERE (RecordType.Name = 'Membership Renewal' AND Active_Membership__c = 'Active') OR (RecordType.Name = 'Membership Prospect' AND Web_Expire_Date__c != null) LIMIT 1) FROM Account WHERE Id =: a.Id]);}

for(Account a : trigger.new){

if(acctmap.get(a.Id).Opportunities.size() != 0){

Opportunity opp = acctmap.get(a.Id).Opportunities[0];

a.Active_Membership_Opportunity__c = opp.Id;}

else {a.Active_Membership_Opportunity__c = null;}

}

}

Any help would be greatly appreciated. Thank you!
6 answers
  1. Sep 21, 2015, 5:49 PM
    Hi Anthony,

    There was a field missing in query.

     I have updated the code. Please replace your code from below code :

     

    trigger act_opp on Account (before insert, before update) {

    List<Opportunity> oppList = new List<Opportunity>([SELECT Id, Name,AccountId FROM Opportunity WHERE AccountID in : trigger.new

    AND ((RecordType.Name = 'Membership Renewal' AND Active_Membership__c = 'Active') OR (RecordType.Name = 'Membership Prospect' AND Web_Expire_Date__c != null))]);

    Map<Id,Opportunity> accIdwithOpp = new Map<Id,Opportunity>();

    for(Opportunity opp : oppList){

    if(!accIdwithOpp.containsKey(opp.AccountId)){

    accIdwithOpp.put(opp.AccountId,opp);

    }

    }

    for(Account acc : trigger.new){

    if(accIdwithOpp.containsKey(acc.id)){

    acc.Active_Membership_Opportunity__c = accIdwithOpp.get(acc.id).id;

    }

    else{

    acc.Active_Membership_Opportunity__c = null;

    }

    }

    }

    Let me know if there is any issue.

    Regards,

    Abhishek
0/9000