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
AtherisAtheris 

Where to add additional loop for a trigger?

Old trigger : convert new Lead to an Account if FirstName, LastName, Email match.
New Email : convert new Lead to an Account if FirstName, LastName, Email match + IsDeleted equals False.

Problem : if there are 2 (or more) accounts in the system with matching FirstName, LastName, Email and one equals as Deleted, then Trigger will allow new Lead to be created to a new Account - even though it should loop through matching Accounts and convert it to Account it matches and isn't set as Deleted.

But where do I add this loop request?
 
trigger LeadAutoConvert on Lead (after insert, after update) 
{
    Map<Id, Lead> newLeadsById = new Map<Id, Lead>([SELECT Id
                                                    , FirstName
                                                    , LastName
                                                    , IsConverted
                                                    , Academic_Title__c
                                                    , BirthDate__c
                                                    , Email
                                                    , Email_Already_In_The_System__c
                                                    , Newsletter_Subscriber__c
                                                    , RecordType__c
                                                    , COM_Web_Form__c 
                                                    , DE_Web_Form__c 
                                                    , FR_Web_Form__c 
                                                    , NO_Web_Form__c 
                                                    , UK_Web_Form__c 
                                                    , US_Web_Form__c 
                                                    , Explorer__c
                                                    , Explorer_Chile_Antarctica__c
                                                    , Explorer_Greenland__c
                                                    , Explorer_Svalbard__c
                                                    , Norway_Coastal__c
                                                    , Norway_Coastal_Autumn__c
                                                    , Norway_Coastal_Winter__c
                                                    , Norway_Coastal_Spring__c
                                                    , Norway_Coastal_Summer__c
                                                    , Norway_Coastal_Port_To_Port__c
                                                    , Norway_Coastal_Round_Trip__c
                                                    , Other_European_Voyages__c
                                                    , Gender__c
                                                    , Nationality__c
                                                    , Mobile__c
                                                    , Phone
                                                    , Web_Form_Address__c
                                                    , Web_Form_Street_No__c
                                                    , Web_Form_Building__c
                                                    , Web_Form_Postal_Code__c
                                                    , Web_Form_City__c
                                                    , Web_Form_Locality__c
                                                    , Web_Form_Region__c
                                                    , Web_Form_Country__c
                                                    , No_Email__c
                                                    , No_Letter__c
                                                    , No_Phone_Call__c
                                                    , No_Sms__c
                                                    , Autumn__c
                                                    , Spring__c
                                                    , Summer__c
                                                    , Winter__c
                                                    , Norway__c
                                                    , Antarctica__c
                                                    , Greenland__c
                                                    , Spitsbergen__c
                                                    , Atlantic_Coast__c
                                                    , Iceland__c
                                                    FROM Lead 
                                                    WHERE Id IN: trigger.new]);
    
    Set<String> leadEmails = new Set<String>();
    
    for(Lead lead : newLeadsById.Values())
    {
        leadEmails.Add(lead.Email);
    }
    
    Map<String, Id> accountRecordTypesByName = new Map<String, Id>();
    for(RecordType accountRecordType : [SELECT Id, Name FROM RecordType WHERE SobjectType =: 'Account'])
    {
        accountRecordTypesByName.Put(accountRecordType.Name, accountRecordType.Id);
    }
    
    List<LeadStatus> convertedLeadStatuses = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted = true LIMIT 1];
    
    //All accounts that match the lead emails.
    List<Account> accounts = [SELECT Id 
                              , FirstName
                              , LastName
                              , PersonEmail
                              , IsDeleted__c
                              FROM Account 
                              WHERE PersonEmail IN: leadEmails];
    
    Map<String, Account> accountsByEmail = new Map<String, Account>();
    
    for(Account account : accounts)
    {
        accountsByEmail.Put(account.PersonEmail, account);
    }
    
    //All the leads that need to be converted into new accounts.
    List<Database.LeadConvert> leadsToConvert = new List<Database.LeadConvert>();
    
    //All the leads that match an existing account. These accounts will be updated and the lead set to converted.
    Set<Id> existingAccountsForLeads = new Set<Id>();
    
    for (Lead lead : newLeadsById.Values())
    {
        //to prevent recursion 
        if (lead.isConverted == false && lead.Email_already_in_the_system__c == false) 
        { 
            Database.LeadConvert leadConvert = new Database.LeadConvert();
            leadConvert.SetLeadId(lead.Id);
            leadConvert.SetDoNotCreateOpportunity(true);
            leadConvert.SetConvertedStatus(convertedLeadStatuses[0].MasterLabel);
            
            //Check whether an account already exists with this lead's email and name. If one already exists we do not need to convert 
            //to a new account as they are already a customer. We rather need to update the existing record.
            Account matchingAccount = accountsByEmail.Get(lead.Email);
            if (matchingAccount != null && matchingAccount.FirstName == lead.FirstName && matchingAccount.LastName == lead.LastName && matchingAccount.IsDeleted__c == false)
            {
                leadConvert.SetAccountId(matchingAccount.Id);
                existingAccountsForLeads.Add(matchingAccount.Id);
            }
            
            leadsToConvert.Add(leadConvert);
        }
    }
    
    Map<Id, Id> accountIdsForLeadIds = new Map<Id, Id>();
    List<Account> accountsToUpdate = new List<Account>();
    if (!leadsToConvert.IsEmpty())
    {
        //Convert all applicable leads into accounts.
        List<Database.LeadConvertResult> convertResults = Database.convertLead(leadsToConvert);
        
        //Keep a mapping of all successful conversions.
        for (Database.LeadConvertResult result : convertResults)
            if (result.IsSuccess())
        {
            accountIdsForLeadIds.Put(result.AccountId, result.LeadId);
        }
        
        accountsToUpdate = [SELECT Id 
                            , PersonTitle
                            , FirstName
                            , LastName
                            , Culture__c
                            , PersonBirthDate
                            , Gender__c
                            , Nationality__c
                            , PersonEmail
                            , Phone
                            , PersonMobilePhone
                            , ShippingStreet__c
                            , ShippingPostalCode__c
                            , ShippingCity__c
                            , ShippingCountry__c
                            , ShippingLocality__c
                            , ShippingStreetNo__c
                            , ShippingRegion__c
                            , ShippingBuilding__c
                            , PersonHasOptedOutOfEmail //ALC_No_Emal__c
                            , NoLetter__pc
                            , PersonDoNotCall
                            , NoSms__pc
                            , Explorer__c
                            , Explorer_Chile_Antarctica__c
                            , Explorer_Greenland__c
                            , Explorer_Svalbard__c
                            , Norway_Coastal__c
                            , Norway_Coastal_Autumn__c
                            , Norway_Coastal_Winter__c
                            , Norway_Coastal_Spring__c
                            , Norway_Coastal_Summer__c
                            , Norway_Coastal_Port_To_Port__c
                            , Norway_Coastal_Round_Trip__c
                            , Other_European_Voyages__c
                            , Autumn__c
                            , Spring__c
                            , Summer__c
                            , Winter__c
                            , Norway__c
                            , Antarctica__c
                            , Greenland__c
                            , Spitsbergen__c
                            , Atlantic_Coast__c
                            , Iceland__c
                            FROM Account 
                            WHERE Id IN: accountIdsForLeadIds.KeySet()];
        
        for (Account accountToUpdate : accountsToUpdate)
        {
            Id matchingLeadId = accountIdsForLeadIds.Get(accountToUpdate.Id);
            if (matchingLeadId == null)
                continue;
            
            Lead matchingLead = newLeadsById.Get(matchingLeadId);
            if (matchingLead == null)
                continue;
            
            //If this is a brand new account (i.e. the lead did not match an existing account) we 
            //need to set some base information.
            if (!existingAccountsForLeads.Contains(accountToUpdate.Id))
            {
                if (matchingLead.COM_Web_Form__c == true || matchingLead.UK_Web_Form__c == true)
                {
                    accountToUpdate.Culture__c = 'English (United Kingdom)';
                    accountToUpdate.Nationality__c = 'UNITED KINGDOM';
                }
                else if (matchingLead.DE_Web_Form__c == true)
                {
                    accountToUpdate.Culture__c = 'German (Germany)';
                    accountToUpdate.Nationality__c = 'GERMANY';
                }
                else if (matchingLead.FR_Web_Form__c == true)
                {
                    accountToUpdate.Culture__c = 'French (France)';
                    accountToUpdate.Nationality__c = 'FRANCE';
                }
                else if (matchingLead.NO_Web_Form__c == true)
                {
                    accountToUpdate.Culture__c = 'Norwegian, Bokmål (Norway)';
                    accountToUpdate.Nationality__c = 'NORWAY';
                }
                else if (matchingLead.US_Web_Form__c == true)
                {
                    accountToUpdate.Culture__c = 'English (United States)';
                    accountToUpdate.Nationality__c = 'USA';
                }
                
                if (matchingLead.BirthDate__c != null)
                    accountToUpdate.PersonBirthDate = matchingLead.BirthDate__c;
                
                //Ensure that the record type is correctly set on the account.
                accountToUpdate.RecordTypeId = accountRecordTypesByName.Get(matchingLead.RecordType__c);
            }
            else
            {
                if (matchingLead.Gender__c != null)
                    accountToUpdate.Gender__c = matchingLead.Gender__c;
                
                if (matchingLead.Nationality__c != null)
                    accountToUpdate.Nationality__c = matchingLead.Nationality__c;
                
                if (matchingLead.Mobile__c != null)
                    accountToUpdate.PersonMobilePhone = matchingLead.Mobile__c;
                
                if (matchingLead.Phone != null)
                    accountToUpdate.Phone = matchingLead.Phone;
                
                if (matchingLead.Web_Form_Address__c != null)
                    accountToUpdate.ShippingStreet__c = matchingLead.Web_Form_Address__c;
                
                if (matchingLead.Web_Form_Street_No__c != null)
                    accountToUpdate.ShippingStreetNo__c = matchingLead.Web_Form_Street_No__c;
                
                if (matchingLead.Web_Form_Building__c != null)
                    accountToUpdate.ShippingBuilding__c = matchingLead.Web_Form_Building__c;
                
                if (matchingLead.Web_Form_Postal_Code__c != null)
                    accountToUpdate.ShippingPostalCode__c = matchingLead.Web_Form_Postal_Code__c;
                
                if (matchingLead.Web_Form_City__c != null)
                    accountToUpdate.ShippingCity__c = matchingLead.Web_Form_City__c;
                
                if (matchingLead.Web_Form_Locality__c != null)
                    accountToUpdate.ShippingLocality__c = matchingLead.Web_Form_Locality__c;
                
                if (matchingLead.Web_Form_Region__c != null)
                    accountToUpdate.ShippingRegion__c = matchingLead.Web_Form_Region__c;
                
                if (matchingLead.Web_Form_Country__c != null)
                    accountToUpdate.ShippingCountry__c = matchingLead.Web_Form_Country__c;
                
                if (matchingLead.No_Letter__c != null)
                    accountToUpdate.NoLetter__pc = matchingLead.No_Letter__c;
                
                if (matchingLead.No_Sms__c != null)
                    accountToUpdate.NoSms__pc = matchingLead.No_Sms__c;
            }
            
            if (matchingLead.Explorer__c == true)
                accountToUpdate.Explorer__c = 'Interested';
                        
            if (matchingLead.Explorer_Chile_Antarctica__c == true)
                accountToUpdate.Explorer_Chile_Antarctica__c = 'Interested';
            
            if (matchingLead.Explorer_Greenland__c == true)
                accountToUpdate.Explorer_Greenland__c = 'Interested';
            
            if (matchingLead.Explorer_Svalbard__c == true)
                accountToUpdate.Explorer_Svalbard__c = 'Interested';
            
            if (matchingLead.Norway_Coastal__c == true)
                accountToUpdate.Norway_Coastal__c = 'Interested';
            
            if (matchingLead.Norway_Coastal_Autumn__c == true)
                accountToUpdate.Norway_Coastal_Autumn__c = 'Interested';
            
            if (matchingLead.Norway_Coastal_Winter__c == true)
                accountToUpdate.Norway_Coastal_Winter__c = 'Interested';
            
            if (matchingLead.Norway_Coastal_Spring__c == true)
                accountToUpdate.Norway_Coastal_Spring__c = 'Interested';
            
            if (matchingLead.Norway_Coastal_Summer__c == true)
                accountToUpdate.Norway_Coastal_Summer__c = 'Interested';
            
            if (matchingLead.Norway_Coastal_Port_To_Port__c == true)
                accountToUpdate.Norway_Coastal_Port_To_Port__c = 'Interested';
            
            if (matchingLead.Norway_Coastal_Round_Trip__c == true)
                accountToUpdate.Norway_Coastal_Round_Trip__c = 'Interested';
            
            if (matchingLead.Other_European_Voyages__c == true)
                accountToUpdate.Other_European_Voyages__c = 'Interested';
            
            if (matchingLead.Autumn__c == true)
                accountToUpdate.Autumn__c = true;
            
            if (matchingLead.Spring__c == true)
                accountToUpdate.Spring__c = true;
            
            if (matchingLead.Summer__c == true)
                accountToUpdate.Summer__c = true;
            
            if (matchingLead.Winter__c == true)
                accountToUpdate.Winter__c = true;
            
            if (matchingLead.Norway__c == true)
                accountToUpdate.Norway__c = true;
            
            if (matchingLead.Antarctica__c == true)
                accountToUpdate.Antarctica__c = true;
            
            if (matchingLead.Greenland__c == true)
                accountToUpdate.Greenland__c = true;
            
            if (matchingLead.Spitsbergen__c == true)
                accountToUpdate.Spitsbergen__c = true;
            
            if (matchingLead.Atlantic_Coast__c == true)
                accountToUpdate.Atlantic_Coast__c = true;
            
            if (matchingLead.Iceland__c == true)
                accountToUpdate.Iceland__c = true;
            
            if (matchingLead.Academic_Title__c != null)
                accountToUpdate.PersonTitle = matchingLead.Academic_Title__c;
            
            if (matchingLead.No_Email__c != null)
                accountToUpdate.PersonHasOptedOutOfEmail = matchingLead.No_Email__c;
            
            if (matchingLead.No_Phone_Call__c != null)
                accountToUpdate.PersonDoNotCall = matchingLead.No_Phone_Call__c;
        }
    }
    
    if (!accountsToUpdate.IsEmpty())
        update accountsToUpdate;
}

 
JeffreyStevensJeffreyStevens
I think your issue is - between 75-89 - where you build the map of Map<Email,Account> - map's have a unique key - so - if there are multiple accounts with the same email - then the 2nd "PUT" just replaces the key/value pair.

I think in this case - you should build a map that looks like this map<email,list<Account>>  (defined like Map<string,list<Account>> - probably call it mAccounts.  I'd populate it like this...
 
map<string,list<Account>> mAccounts = new map<string,list<Account>>();
for(Account account :accounts) {
    list<Account> iterAccounts = new list<Account>();
   if(mAccounts.containsKey(account.email)) {
        iterAccounts = mAccounts.get(account.email);
   }
   iterAccounts.add(account);
   mAccounts.put(account.email,iterAccounts);
}

// Now you have a populated map of <Email,List<Account>>

then - at 109 - where you just do a get of the accountsByEmail - you need to so something similar - get list of accounts by email - then loop through that list.

HTH