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
sumit dsumit d 

Duplicate id in List Error

Hi All, 
          I am getting this error in Class: LeadTrigger: execution of AfterInsert caused by: System.ListException: Duplicate id in list: 00Q8I000006zCO1UAM Class.LeadTriggerHelper.markPrimary: line 168, column 1 Trigger.LeadTrigger: line 14, column 1
My class is given below:- 

public class LeadTriggerHelper {
    
    public static List<Lead> newLeads = new List<Lead>();
    public static List<Lead> oldLeads = new List<Lead>();
    public static Map<Id, Lead> newMapLeads = new Map<Id, Lead>();
    public static Map<Id, Lead> oldMapLeads = new Map<Id, Lead>();
    public static Boolean runTrigger = true;
    private static Map<String, Schema.SObjectField> leadFieldsMap = Lead.SObjectType.getDescribe().fields.getMap();
    
    
    public static void markPrimary(){
        
        Map<String, List<Lead>> mapKeyToAssociatedLeads = new Map<String, List<Lead>>();
    List<String> fields = getFieldsString(); 
    List<Lead> applicableLeads = (Lead[]) Database.query('SELECT ' + String.join(fields, ',') +
                                                        ' FROM Lead WHERE Id IN :newLeads');

    Set<String> leadEmails = new Set<String>();
    Set<String> nameAndPhoneKeys = new Set<String>();
    Set<String> phones = new Set<String>();
    Set<String> names = new Set<String>();

    List<Lead> leadsToUpdate = new List<Lead>();
    for (Lead leadObj : applicableLeads) {
        if (leadObj.Email != null) {
            leadEmails.add(leadObj.Email);
        }
        names.add(leadObj.Name);
        phones.add(leadObj.Phone);
        nameAndPhoneKeys.add(leadObj.Name + leadObj.Phone);
    }

    String leadQuery = 'SELECT ' + String.join(fields, ',') +
                       ' FROM Lead WHERE (Email IN :leadEmails OR (Name IN :names AND Phone IN :phones))' +
                       ' AND Id NOT IN :applicableLeads AND IsConverted = False AND Lead_Type__c != \'Primary Converted\'' +
                       ' ORDER BY CreatedDate ASC';

    String personAccountQuery = 'SELECT Id, PersonEmail, PersonMobilePhone, Full_Name__pc ' +
                                ' FROM Account WHERE (PersonEmail IN :leadEmails OR ' +
                                ' (Full_Name__pc IN :names AND PersonMobilePhone IN :phones))';
        
        System.debug('personAccountQuery'+personAccountQuery);

    List<SObject> combinedResults = new List<SObject>();
    combinedResults.addAll(Database.query(leadQuery));
    combinedResults.addAll(Database.query(personAccountQuery));
        System.debug('combinedResults'+combinedResults);

    for (SObject existingRecord : combinedResults) {
        if (existingRecord.getSObjectType() == Lead.SObjectType) {
            Lead existingLead = (Lead) existingRecord;

            if (leadEmails.contains(existingLead.Email)) {
                if(mapKeyToAssociatedLeads.containsKey(existingLead.Email)) {
                List<Lead> associatedLeads = mapKeyToAssociatedLeads.get(existingLead.Email);
                associatedLeads.add(existingLead);
                mapKeyToAssociatedLeads.put(existingLead.Email, associatedLeads);
            }  
            else {
                mapKeyToAssociatedLeads.put(existingLead.Email, new List<Lead> {existingLead});
            }
            }

            if (nameAndPhoneKeys.contains(existingLead.Name + existingLead.Phone)) {
                if(mapKeyToAssociatedLeads.containsKey(existingLead.Name+existingLead.Phone)) {
                List<Lead> associatedLeads = mapKeyToAssociatedLeads.get(existingLead.Name+existingLead.Phone);
                associatedLeads.add(existingLead);
                mapKeyToAssociatedLeads.put(existingLead.Name+existingLead.Phone, associatedLeads);
            }  
            else {
                mapKeyToAssociatedLeads.put(existingLead.Name + existingLead.Phone, new List<Lead> {existingLead});
            }
            }

            // Check if it's a matching person account
         } else if (existingRecord.getSObjectType() == Account.SObjectType) {
             Account matchingPersonAccount = (Account) existingRecord;
               System.debug('matchingPersonAccount'+matchingPersonAccount);
            
         String personAccountKey = matchingPersonAccount.PersonEmail != null ? matchingPersonAccount.PersonEmail : (matchingPersonAccount.Full_Name__pc + matchingPersonAccount.PersonMobilePhone);
        if (!mapKeyToAssociatedLeads.containsKey(personAccountKey)) {
            mapKeyToAssociatedLeads.put(personAccountKey, new List<Lead>());
        }
             System.debug('mapKeyToAssociatedLeads'+mapKeyToAssociatedLeads);

        for (Lead leadObj : applicableLeads) {
            if (leadObj.Email != null && leadObj.Email == matchingPersonAccount.PersonEmail) {
                mapKeyToAssociatedLeads.get(personAccountKey).add(leadObj);
                
            } else if (leadObj.Name != null && leadObj.Phone != null && (leadObj.Name + leadObj.Phone) == (matchingPersonAccount.Full_Name__pc + matchingPersonAccount.PersonMobilePhone)) {
                mapKeyToAssociatedLeads.get(personAccountKey).add(leadObj);
            }
        }
            
            System.debug('mapKeyToAssociatedLeads Line 94'+mapKeyToAssociatedLeads);
            
             for (Lead leadObj : applicableLeads) {
                System.debug('mapKeyToAssociatedLeads'+mapKeyToAssociatedLeads);
                if (mapKeyToAssociatedLeads.containsKey(leadObj.Email) && mapKeyToAssociatedLeads.get(leadObj.Email).contains(leadObj)) {
                    leadObj.Person_Account__c = matchingPersonAccount.Id;
                    System.debug('leadObj.Person_Account__c'+leadObj.Person_Account__c);
                } else if (mapKeyToAssociatedLeads.containsKey(leadObj.Name + leadObj.Phone) && mapKeyToAssociatedLeads.get(leadObj.Name + leadObj.Phone).contains(leadObj)) {
                    leadObj.Person_Account__c = matchingPersonAccount.Id;
                    System.debug('leadObj.Person_Account__c'+leadObj.Person_Account__c);
                }
            }
        }
    }
        
        List<Lead> associatedLeads = new List<Lead>();
        Map<Id, Lead> mapNewLeadToAssociatedLead = new Map<Id, Lead>();
        for(Lead leadObj : applicableLeads){
            
            if(mapKeyToAssociatedLeads.containsKey(leadObj.Email)){
                associatedLeads = mapKeyToAssociatedLeads.get(leadObj.Email);
                mapNewLeadToAssociatedLead.put( leadObj.Id, associatedLeads.get(0) );
            }
            else if(mapKeyToAssociatedLeads.containsKey(leadObj.Name+leadObj.Phone)){
                associatedLeads = mapKeyToAssociatedLeads.get(leadObj.Name+leadObj.Phone);
                mapNewLeadToAssociatedLead.put( leadObj.Id, associatedLeads.get(0) );
            }
        }
        
        System.debug('mapNewLeadToAssociatedLead'+mapNewLeadToAssociatedLead);
        
        // loop over new inserted leads
        for(Lead leadObj : applicableLeads){
            
            Lead primaryLead;
            if( mapNewLeadToAssociatedLead.containsKey( leadObj.Id )) {
                primaryLead = mapNewLeadToAssociatedLead.get( leadObj.Id );
            }
            System.debug('primaryLead'+primaryLead);
            if( primaryLead != null ) {
                primaryLead.Lead_Type__c = 'Primary';
                // update new lead to existing type        
                leadObj.Lead_Type__c = 'Existing Lead';
                leadObj.Primary_Lead__c = primaryLead.Id;
                //leadObj.OwnerId = primaryLead.OwnerId;
                runTrigger = false;
                leadsToUpdate.add(leadObj);
                System.debug('leadsToUpdate'+leadsToUpdate);
                Schema.SObjectType leadType = leadObj.getSObjectType();
                
                for(String fieldName : leadFieldsMap.keySet()){
                    if(fieldName != 'Primary_Lead__c'){
                        if(leadFieldsMap.get(fieldName).getDescribe().isUpdateable()){
                            Object associatedLeadFieldValue = leadObj.get(fieldName);
                            Object primaryLeadFieldValue = primaryLead.get(fieldName);
                            
                            if (primaryLeadFieldValue == null && associatedLeadFieldValue != null) {
                                primaryLead.put(fieldName, associatedLeadFieldValue);
                            }    
                        }
                    }
                }
                leadsToUpdate.add(primaryLead); 
                 System.debug('primaryLead'+primaryLead);
            }
            else {
                leadObj.Lead_Type__c = 'Primary';
                leadsToUpdate.add(leadObj);
                System.debug('leadObj'+leadObj.Lead_Type__c);
            }
        }
        if(leadsToUpdate.size() > 0){
              System.debug('leadsToUpdate'+leadsToUpdate);
             update leadsToUpdate; // Getting error here
         }
    }
         }
Can anyone help me to remove this error from this class?
HarshHarsh (Salesforce Developers) 
Hi Sumit,

Please check the similar reference in the below link.

https://help.salesforce.com/s/articleView?id=000382864&type=1  

As per the resolution given in the link please modify your code

Please mark it as Best Answer if the above information was helpful.

Thanks.




Important Update - what you need to do
User-added image
As a reminder, on December 4, 2023 the Salesforce Discussion Forums will be removed from the Salesforce Developers website. These forums will shut down and all relevant discussions will migrate to the Trailblazer Community digital platform.

During the week starting November 20, you can view discussions, but not post new questions or responses. On December 4, you will no longer be able to access the discussion forums from the Salesforce Developers website.

Please take these steps before November 30, 2023, 11:59 p.m. PT to ensure your contributions follow you to the Trailblazer Community:
  1. If you’re not already a member of the Trailblazer Communitysign up for a Trailblazer account using the same login email address associated with your Developer Discussion Forums account. This is crucial.
  2. If you already have a Trailblazer account, and it’s using a different email address from your Developer Discussion Forums account, we recommend that you log in to the Trailblazer Community and connect your forums email address to your Trailblazer account.
Find more info & support
We know that moving platforms can be a hassle, so we created a special forums users group, the Migration Support Hub, in the Trailblazer Community where you can get training videos, information, and assistance.

We are here to help you through this transition!

Sincerely,
The Forums Support Team
sumit dsumit d
I got another error when i did this :- System.DmlException: Update failed. First exception on row 0 with id 00Q8I000006zCU9UAM; first error: CIRCULAR_DEPENDENCY, Hierarchy Constraint Violation: [Primary_Lead__c] Class.LeadTriggerHelper.markPrimary: line 177, column 1 Trigger.LeadTrigger: line 14, column 1
I updated as BELOW:- 
/*if(leadsToUpdate.size() > 0){
              System.debug('leadsToUpdate'+leadsToUpdate);
             update leadsToUpdate;
         }*/
        
        map<id,Lead> LeadMapToUpdate = new map<id,Lead>();
        
        //put all the values from the list to map. 
        LeadMapToUpdate.putall(leadsToUpdate);
        if(LeadMapToUpdate.size()>0){
             System.debug('LeadMapToUpdate'+LeadMapToUpdate);
            update LeadMapToUpdate.values();
        }