You need to sign in to do that
Don't have an account?
compare lead email to contact email and update custom lead field when duplicate found
Hi All,
I am trying to update a custom field (NetNewLead__c) when a Lead's Email doesn't exist in Contact Email.
I am thinking a Trigger is the best solution, but my Apex skills are lacking.
I do not want to prevent creation of the Lead.
Can someone take a look at my code and offer advice?
Kind regards,
Robert
Code is below
trigger NetNewLead_Trigger on Lead (after update) {
class UniqueKey {
UniqueKey(String email) {
this.email = email;
}
string Email;
integer hashCode() {
return toString().hashCode();
}
boolean equals(Object o) {
return toString() == ((UniqueKey)o).toString();
}
public override string toString() {
return String.format(
'Email = \'\'{0}\'\'',
new String[] {
Email==null?'':String.escapeSingleQuotes(Email.tolowercase())
}
);
}
}
Map<UniqueKey, Lead> leads = new Map<UniqueKey, Lead>();
for(Lead record:Trigger.new) {
if(record.isconverted) {
UniqueKey key = new UniqueKey(record.email);
if(leads.containskey(key)) {
record.addError('Duplicate lead conversion.');
} else {
leads.put(key, record);
}
}
}
String[] keys = new String[0];
for(UniqueKey key:leads.keyset()) {
keys.add(key.tostring());
}
String query = string.format(
'SELECT Id,Email,RecordTypeId FROM Contact WHERE RecordTypeId =:Client Contact" and {0}',
new String[] {
String.join(keys, ' OR ')
}
);
if(!leads.isempty()) {
for(Contact record:Database.query(query)) {
UniqueKey key = new UniqueKey(record.email);
if(leads.containskey(key)) {
leads.get(key).addError('Duplicate lead conversion.');
}
}
}
}
Please use below code, this should fulfill your use case. I have put it comments so that the code becomes self explanatory. Note that I have only handled the insertion of leads, you can modify it if you want to handle update scenarios also.
All Answers
Ravi,
Thanks for your reply.
I created Lead.NetNewLead__c with a default value of True. If the Contact.Email from Lead.Email already exists I want to change Lead.NetNewLead__c to False.
I applogize in advance for my code.
Kind regards,
Robert
Please use below code, this should fulfill your use case. I have put it comments so that the code becomes self explanatory. Note that I have only handled the insertion of leads, you can modify it if you want to handle update scenarios also.
Thank you so much!
When I try to save I am getting errors.
I should not have saved LeadTrigger before LeadTriggerHandler...that is the first error (line 4).
Not sure what is causing LeadTriggerError "invalid parameter value"