function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mpatelmpatel 

Trigger for checking New Leads and Contacts

I was wondering if anyone could help in creating a trigger that checks both Leads and Contacts before inserting a Lead into Salesforce.

 

I have the example for checking just a new Lead but I need a trigger that will check both Leads and Contacts before allowing it to be submitted into salesforce.

 

 

thank you

Best Answer chosen by Admin (Salesforce Developers) 
SelectedPartnerSelectedPartner

The format of the  former post is messed up, so i post it agian

 

trigger LeadCreateTrigger on Lead (before insert) { for (Lead lead : Trigger.new) { Lead[] leads = [SELECT Name, Email FROM Lead WHERE Email = :lead.Email And Email !='' LIMIT 1]; if ( leads.size() > 0 ) { lead.addError('Lead \'' + leads[0].Name + '\' with the email address \'' + leads[0].Email + '\' already exist!'); } Contact[] cons = [SELECT Name, Email FROM Contact WHERE Email = :lead.Email And Email !='' LIMIT 1]; if ( cons.size() > 0 ) { lead.addError('Contact \'' + cons[0].Name + '\' with the email address \'' + cons[0].Email

+ '\' already exist!'); } } }

 

All Answers

SelectedPartnerSelectedPartner
I assume that you wanna choose the email address as the filter criteria, the code following is for your reference: 

trigger LeadCreateTrigger on Lead (before insert) { for (Lead lead : Trigger.new) { Lead[] leads = [SELECT Name, Email FROM Lead WHERE Email = :lead.Email And Email != ' ' And Email !='' LIMIT 1]; if ( leads.size() > 0 ) { lead.addError('Lead \'' + leads[0].Name + '\' with the email address \'' + leads[0].Email + '\' has already exist!'); } Contact[] contacts = [SELECT Name, Account.Name, Email FROM Contact WHERE Email = :lead.Email And Email != ' ' And Email !='' LIMIT 1]; if ( contacts.size() > 0 ) { lead.addError('Contact \'' + contacts[0].Name + '\' From \'' + contacts[0].Account.Name + '\' with the email address \'' + contacts[0].Email + '\' has already exist!'); } }}

 

SelectedPartnerSelectedPartner

The format of the  former post is messed up, so i post it agian

 

trigger LeadCreateTrigger on Lead (before insert) { for (Lead lead : Trigger.new) { Lead[] leads = [SELECT Name, Email FROM Lead WHERE Email = :lead.Email And Email !='' LIMIT 1]; if ( leads.size() > 0 ) { lead.addError('Lead \'' + leads[0].Name + '\' with the email address \'' + leads[0].Email + '\' already exist!'); } Contact[] cons = [SELECT Name, Email FROM Contact WHERE Email = :lead.Email And Email !='' LIMIT 1]; if ( cons.size() > 0 ) { lead.addError('Contact \'' + cons[0].Name + '\' with the email address \'' + cons[0].Email

+ '\' already exist!'); } } }

 

This was selected as the best answer
mpatelmpatel

Thank you very much that is exactly what I needed.