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
Michael Hedrick 2Michael Hedrick 2 

Duplicate trigger still allowing duplicate record

Hello All.
I have a class that looks for existing Leads with the same email address. 
If the email address exist add a task to the existing Lead.  This works.
The issue is that is still allows the creation of the duplicate Lead.  I do not want to throw an error message since the Leads may be imported via data loader.  If its creating a task because the email address already exist it should not be creating the lead.
Thanks,
M
trigger LeadPreventDuplicate on Lead (before insert,before update) {

    Map<String, Lead> leadMap = new Map<String, Lead>();
    for (Lead lead : System.Trigger.new) {
        
       //  Make sure we don't treat an email address that isn't changing during an update as a duplicate.  
    
        if ((lead.Email != null) && (System.Trigger.isInsert ||
                (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) {
                leadMap.put(lead.Email, lead);
       }
    }
    
    List<task> addtask=New List<task>();
    for (Lead lead : [SELECT Email FROM Lead
                      WHERE 
                      Email IN :leadMap.KeySet()]) {
        Lead newLead = leadMap.get(lead.Email);
        
       // newLead.Email.addError('A lead with this email '
                        //       + 'address already exists.');
        addtask.add(new Task(
        WhoID =lead.id, 
        Status = 'Active',
        Subject = 'Test Task',
        ActivityDate = system.today()
        ));
        
       } 
         insert addtask;        
                                                            
}

 
Best Answer chosen by Michael Hedrick 2
Raju yadavRaju yadav
Hi Michael Hedrick 2,
You have to add error to prevent the insertion of lead.
I have check with data loader which allow all data to insert prevent only that have an error.

Thanks,

All Answers

Raju yadavRaju yadav
Hi Michael Hedrick 2,
You have to add error to prevent the insertion of lead.
I have check with data loader which allow all data to insert prevent only that have an error.

Thanks,
This was selected as the best answer
Michael Hedrick 2Michael Hedrick 2
Thank you both for the replies.
Sitanshu, I will look further into the link you sent.
Raju, yes if I leave the error message in the insert of the duplicate Lead fails but the activity is also not created on the lead record that was found with the matching email address.  And there lies my issue.

Thanks,
M