I am trying to do a trigger to avoid lead duplication. Unfortunately I cant use the duplicate manager rule of Salesforce as most of the leads that are created in the system comes from a wordpress gravity form. If I use the salesforce duplicate rule the people who fill the form will not get any error message (it seems that is just the way it is with this wp pluggin)
Basically what I want to do is, if someone is creating a new lead either from salesforce or the webform, if the lead is already in the system (I have a formula field that is the first + last name + email) and it havent been converted, it updates the already existing lead. If the already existing lead was converted, I want to create an opportunity.
If someone is editing a lead and becomes a duplicate, unallow to save having an error message.
I have done the following, so for some reason this is firing twice. Maybe I am approaching this the wrong way, so if anyone has any suggestion will be very appreciate it.
Also is this possible to do in process builder, I try but I cant see the way to check for duplicates in process builder
Trigger:
trigger lead_BIBA on Lead (before insert, before update) {
Lead_HDL_BIBU handler = new Lead_HDL_BIBU();
if(Trigger.isInsert && Trigger.isBefore) {
handler.OnBeforeInsert(Trigger.new,Trigger.old);
}else if(Trigger.isUpdate && Trigger.isBefore) {
handler.OnBeforeUpdate(Trigger.new,Trigger.old);
}
}
Lead_HDL_BIBU
Also I dont think I am following best practices as I dont see a different way that doing a query in a for loop
public with sharing class Lead_HDL_BIBU {
public void OnBeforeInsert(List<Lead> newRec,List<Lead> oldRec){
updateRecords(newRec,oldRec);
}
public void OnBeforeUpdate(List<Lead> newRec,List<Lead> oldRec){
updateRecords(newRec,oldRec);
}
private void updateRecords(List<Lead> newRec,List<Lead> oldRec) {
List<Lead> toCheck = new List<Lead>();
String uniqueName;
Boolean IsNew = false;
if(oldRec == null){
IsNew=true;
}
for(Lead l:newRec){
uniqueName = l.UniqueMatchingRule__c;
toCheck = [SELECT UniqueMatchingRule__c, IsConverted FROM Lead WHERE UniqueMatchingRule__c=:uniqueName];
if(toCheck.size()>0){
if(IsNew == false ){
newRec[0].addError('Duplicate Error: There is already a Lead in the system with the same Names and Email address, You can: Update the already existing lead or Delete the existing lead and update this lead, Cancel and delete this lead or proceed to create a new Opportunity (not sure ifthis is the right message)');
}else{
/*
if(toCheck[0].IsConverted == true){
//create an opportunity
}else{
//Update the lead
toCheck[0] = l;
update toCheck[0];
}
*/
}
}
}
}
}