I have a use case to link a case records created for a lead record. If lead record gets converted then the related cases should be automatically linked to the converted contact and account record. Please help to check and correct my code below (I am new here, so your help is appreciated.)
public class LeadTriggerHandler {
public static void updateRelatedContactWithCase(List<Lead> leList, Map<Id, Lead> leOldMap){
List<case> caList = new List<case>();
Set<Id> leIds = new Set<Id>();
for(Lead le : leList){
if(le.Status == 'Closed - Converted' && leOldMap.get(le.Id).Status != 'Closed - Converted'){
if(le.Status == 'Closed - Converted')
leIds.add(le.Id);
}
System.debug(leIds);
}
// To update Lead related Contact to link the case record related to the Lead which was converted.
if(!leIds.isEmpty()){
for(Lead le = [SELECT Id, Status,
(SELECT Id, Lead__c, AccountId, ContactId FROM Cases__r) FROM Lead WHERE Id IN: leIds]){
if(le.cases__r !=null){
for(Cases__r ca : le.Cases__r){
ca.ContactId = le.ConvertedContactId;
caList.add(ca);
}
}
if(!caList.isEmpty()){
update caList;
}
}
}
}
}