You need to sign in to do that
Don't have an account?
Aaron Hill
Refactoring Code after "Apex CPU time limit exceeded:-"
We have a lead/account relationship. I created a lead field called "Related Account", which is a lookup field. The lead is then added to a related list in the account view. I wrote the following so that when a lead was updated, the related account trigger would automatically find the matching account and populate the field with that information. It works great on an indiviual basis but not at all when I try to bulk update more than a handful of leads. The full error is:
"CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:updateRelatedAccount: System.LimitException: Apex CPU time limit exceeded:--".
My question: can this code be refactored so that it works for bulk updates? And if so, how?
Thanks for your time.
"CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:updateRelatedAccount: System.LimitException: Apex CPU time limit exceeded:--".
My question: can this code be refactored so that it works for bulk updates? And if so, how?
Thanks for your time.
trigger updateRelatedAccount on Lead (before update) { List<Account> accList = [SELECT Id, Name FROM Account]; for (Lead lead : System.Trigger.new) { for (Account acc : accList) { if (lead.Company != '' && lead.Company == acc.Name) { lead.Related_Account__c = acc.Id; } } } }
set<string> accNames = new set<string>();
for(Lead ld : Trigger.New){
accNames.add(ld.Company);
}
list<Account> accs = new list<Account>([Select Id,Name from account where name=:accNames]);
map<String,id> mapaccs = new map<String,id>();
for(Account ac : accs){
mapaccs.put(ac.Name,ac.Id)
}
for(Lead lds : Trigger.New){
lds.related_account__c = mapaccs.get(lds.company).Id;
}
All Answers
set<string> accNames = new set<string>();
for(Lead ld : Trigger.New){
accNames.add(ld.Company);
}
list<Account> accs = new list<Account>([Select Id,Name from account where name=:accNames]);
map<String,id> mapaccs = new map<String,id>();
for(Account ac : accs){
mapaccs.put(ac.Name,ac.Id)
}
for(Lead lds : Trigger.New){
lds.related_account__c = mapaccs.get(lds.company).Id;
}
I recieved the following error: "Initial term of field expression must be a concrete SObject: Id"
For line 15
for(Lead lds : Trigger.New){
if(mapaccs.containskey(lds.compamy)){
lds.related_account__c = mapaccs.get(lds.company).Id;
}
}