Wednesday, January 18, 2023

Trigger for Lead Email and Contact Email is Same Convert Lead to Existing Contact in Salesforce

Apex Trigger

trigger LeadEmailContactEmailSameUpdateCon on Lead (after insert) {
    LeadEmailAndContactEmailSameConvertLead.ConvertleadWithSameEmail(Trigger.New);

Apex Class

public class LeadEmailAndContactEmailSameConvertLead {
    public Static void ConvertleadWithSameEmail(List<Lead> lea){
        Map<String,lead>   mapemailleads = new Map<String,lead>();
        for(Lead l:lea) {
            if(l.Email != Null){
                mapemailleads.put(l.email,l);
            }
        }
        List<Contact> ContactEmail=[select id,LastName,Email,AccountId                                      
                                    from Contact 
                                    where  
                                    Email IN:mapemailleads.keySet() 
                                   ]; 
        
        if( !ContactEmail.isEmpty() || ContactEmail.size() > 0)     {
            for(Contact c:ContactEmail){
                Lead newlead = mapemailleads.get(c.Email);
                Database.LeadConvert lc = new database.LeadConvert();
                lc.setLeadId(newlead.id);
                lc.setAccountId(c.AccountId);
                lc.setContactId(c.ID);
                lc.setDoNotCreateOpportunity(true); 
                LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus 
 WHERE IsConverted=true LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
                Database.LeadConvertResult lcr = Database.convertLead(lc);                
                System.assert(lcr.isSuccess()); 
            }
        } else{
            for (Lead lead: lea) {
                Database.LeadConvert lc = new database.LeadConvert();
                lc.setLeadId(lead.id);
                lc.setDoNotCreateOpportunity(true); 
                LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus 
WHERE IsConverted=true LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
                Database.LeadConvertResult lcr = Database.convertLead(lc);                
                System.assert(lcr.isSuccess()); 
            }
            
        }
        
    }
}

No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...