Example : On Lead we have custom lookup field named Company Owner(User), also Company(Account) field. On Account we have custom field called CEO(User), While creating Lead If Linked Company has SEO then populate that in Company Owner.
Solution
LeadTriggerHandler
public class LeadTriggerHandler {
// Approach 1 Single Record
public static void updateLeadBeforeInsert(List<Lead> leadDetails) {
System.debug(leadDetails);
Id accId = leadDetails[0].Company__c;
System.debug(leadDetails[0].Company__c);
List<Account> account = [Select Id, CEO__c From Account where Id=: accId];
System.debug(account);
leadDetails[0].Company_Owner__c = account[0].CEO__c;
}
// Approach 2 Bulk Records
public static void updateBulkLeadsBeforeInsert(List<Lead> leadDetails){
// Prepare all Account Ids
Set<id> accIds = new Set<Id>();
For(Lead lead: leadDetails) {
accIds.add(lead.Company__c);
}
List<Account> accounts = [Select Id, CEO__c From Account where Id in: accIds];
Map<Id, Account> accountsRecMap = New Map<Id, Account>(accounts);
System.debug(accountsRecMap);
For(Lead lead: leadDetails) {
if(accountsRecMap.containsKey(lead.Company__c)) {
Account acc = accountsRecMap.get(lead.Company__c);
lead.Company_Owner__c = acc.CEO__c;
}
}
}
}
LeadTrigger
trigger LeadTrigger on Lead (before insert) {
if(trigger.isBefore && trigger.isInsert) {
LeadTriggerHandler.updateLeadBeforeInsert(trigger.new);
}
}