0

When duplicate record found based on either Phone or Email then only duplicateRecord(Checkbox field) should be checked.

I wrote the trigger to check duplicate record based on Phone or email but it is not working. It will check the checkbox even if the new created record is not duplicate

trigger Duplicate on Lead (before insert,before update) {

Set<String> leadEmail = new Set<String>();
Set<String> leadPhone = new Set<String>();
for(Lead leadRecords : [SELECT Id,Email,Phone FROM Lead WHERE Email != NULL OR Phone != NULL]){
    leadEmail.add(leadRecords.email);
    leadPhone.add(leadRecords.phone);
}
for (Lead lead : Trigger.new)
{
    if(lead.email != null || lead.phone != null){
        if(leadEmail.Contains(lead.email) || leadPhone.contains(lead.phone)){
            lead.duplicateRecord__c = true;
        }
    }
}
}
  • Querying all leads is a terrible idea. This functionality will not work on a large system. Why are you not pursuing OOB duplicate management? – Adrian Larson Apr 1 '16 at 12:08
1

In your query

[SELECT Id,Email,Phone FROM Lead WHERE Email != NULL OR Phone != NULL]

You can select a Lead with null Email or Phone because of OR (i.e. Email is null and Phone is 777) Then you add that null to your Set and again because of || you will populate your checkbox.

To fix this you can for example add a check for null where you are adding records to a Set:

if(leadRecords.email != null){
    leadEmail.add(leadRecords.email);
}
if(leadRecords.phone != null){
    leadPhone.add(leadRecords.phone);        
}

Also before coding anything you can consider using built-in functionality as suggested in the comments.

  • I tried this also but till same problem facing me – user29314 Apr 1 '16 at 12:33
  • Have you tried using debug logs and see what fields are in your set and what are in the new Lead? – Oles Malkov Apr 1 '16 at 12:37
  • I am not getting what actually I've to do – user29314 Apr 2 '16 at 6:22
  • I've noticed that you have a before update trigger, so in update case you will always add email or phone of a Lead to your Set and your checkbox will be always true. Try adding to your query (Email != NULL OR Phone != NULL) AND Id NOT in :Trigger.new – Oles Malkov Apr 2 '16 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.