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
sfdc_1sfdc_1 

using trigger i have scenario 1.create a formula filed domain on lead 2. so, if email filed on lead is abc@xyz.com- domain will be xyz. 3 insert a new lead-take the domain and search system with the same domain for existing lead.

using trigger i have to do scenario 1.create a formula filed domain on lead 2. so, if email filed on lead is abc@xyz.com- domain will be xyz. 3 insert a new lead-take the domain and search system with the  same  domain for existing lead.4. if match found take most recent modified lead and take owner from that lead and assign the same owner to new lead .

plzz let meknow using trigger
yogesh_patilyogesh_patil
Hello ,

Run the below logic in before insert context

public class LeadTriggerHandlerService{
    public static void updateOwnerOfLeadFromDomain(List<Lead> newList){
    Set<Strig> setDomainName = new Set<String>();
    Map<String,String> mapLeadDomainToLeadOwnerId = new Map<String,String>();
        for(Lead objLead:newList){
            setDomainName.add(objLead.Domain__c);
        }
        
        for(Lead objLead: [SELECT Id,OwnerId,Domain__c FROM LEAD WHERE Domain__c IN: setDomainName ORDER BY LastModifiedDate DESC]){
            mapLeadDomainToLeadOwnerId.put(objLead.Domain__c,objLead.OwnerId);
        }
        
        for(Lead objLead:newList){
            if(mapLeadDomainToLeadOwnerId!=null && !mapLeadDomainToLeadOwnerId.isEmpty() && mapLeadDomainToLeadOwnerId.containsKey(objLead.Domain__c)){
                objLead.OwnerId = mapLeadDomainToLeadOwnerId.get(objLead.Domain__c);
            }
        }
    }
}