+ Start a Discussion
MiguelGuerreiroMiguelGuerreiro 

Error on Contact Trigger

Hello,

 

I'm really new to Apex so I request once more the community help! 

 

I've done this trigger below to prevent duplicete contacts (based on the email). Does anyone see a big flaw in it?

 

 

trigger PreventDuplicates on Contact (before insert, before update) { Contact[] contacts = [select Email,Id from Contact]; for(Contact c: Trigger.new) { for(Integer i = 0; i < contacts.size(); i++) { if(contacts[i].Email == c.Email) { c.Email.addError('Duplicated email address.'); } } } }

 

 

 

 

 

jkucerajkucera

It will blow up if you try to create 100 contacts and 100 exist as the loop will have more than the 10k allowed statements.

 

A more scalable way is to return a list of all contacts that have a matching email address via query vs loop.  There's definitely still more room to optimize this, but should work up to around 50 duplicates in a batch of 200 contacts:

trigger PreventDuplicates on Contact (before insert, before update) { String emailAddresses=" "; for(Contact c: Trigger.new) { emailaddresses=c.Email +","; }//for

Contact[] dupes=[select id, email from contact where email=:emailaddresses LIMIT 1000];

for(Contact c: Trigger.new){

for (Contacte dupe:dupes){

 if (c.email=dupe.email){

 c.email.adderror('Duplicate email address.');

}

//throw an error for contacts where email address matches

}

}

 

:

 

 

MiguelGuerreiroMiguelGuerreiro
Could you please explain:

jkucera wrote:

It will blow up if you try to create 100 contacts and 100 exist as the loop will have more than the 10k allowed statements.

 

 


jkucerajkucera

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_gov_limits.htm

 

The limit for Total # executed script statements initiated from a trigger is 10,000.  Therefore if you have a nested loop, you'll execute the same statement X*Y times where X = # triggered Contacts and Y=# Total contacts.  100*100 = 10k.  

 

Using a query to only return relevant contacts & then using a set to remove duplicates makes this operation much smaller, to the point where the worst case you'll see is 200x200 = 40k statements, but this would only happen when you try to import 200 contacts and all 200 in that batch are duplicates.  

 

Given you want to surface the error at runtime, an asynchronous call nor batch call works well, so you'll want to optimize your code to prevent the statement limit from occurring.

MiguelGuerreiroMiguelGuerreiro

It is clear now! Thank you for the explanation.