The below code searches on the lead record if the Account already exists in Salesforce using the website/email domain field. The code works just fine but I keep getting this error in my inbox: System.LimitException: Apex CPU time limit exceeded
Trigger Accname on Lead (before insert, before update) {
Account[] accts = [SELECT Name, id,Website,Domain__c FROM Account WHERE (Website != NULL OR Domain__c != NULL)];
for(Lead l : Trigger.new)
{
for(Integer i = 0; i < accts.size(); i++)
{
if(l.Domain__c == accts[i].Domain__c || l.Domain__c == accts[i].Website)
{
l.Account_Leads__c = accts[i].id;
l.Account_Found__c = True;
} else(System.debug('Not triggered.'));
}
}
}
Best Answer
Try at least restricting to
Account
records which might match, and mapping by those values.Then in your trigger you would call
LeadService.findAccountsByDomain(trigger.new);
.Note that you may have multiple records that match the same key, but you are arbitrarily choosing one. This means your code is not deterministic. You should also look up trigger handlers and find a pattern that works for you to implement logic-less triggers.