I have a one to many relationship between Project and Insurance object. When a record is created on Insurance object, it needs to get the Project record and then count how many Insurance records are present and it needs to input the value in the Name field of the Insurance record.
The below code does that exactly but it inserts the records based on the order it receives it. When I try to mass upload the Insurance__c using excel, the record that I insert first gets inserted and assigned a reference as INS-001 and so on.
The sequence will be incorrect if the records are not in order. For that reason, I want to sort it by start date field in the Insurance__c object. I have tried the below logic where I tried to use a map but totally confused on how to implement the sorting logic so that all the Insurance records are sorted based on the start date and then it can be passed to the 3rd for loop for Name assignment.
Trigger
trigger InsuranceTrigger on Insurance__c (before insert) {
SWITCH ON Trigger.operationType {
WHEN BEFORE_INSERT{
InsuranceClass.insuranceAutomation(Trigger.new);
}
}
}
Apex Class:
public class InsuranceClass {
public static void insuranceAutomation(List<Insurance__c> insuranceList){
Set<Id> projectIds = new Set<Id>();
//Get all the project Id for the corresponding new insurance records
for(Insurance__c i : insuranceList){
projectIds.add(i.Project__c);
//system.debug(insuranceIds);
}
//Sorting logic
Map<Insurance__c, Date> insList1 = new Map<Insurance__c, Date>();
for(Insurance__c iList : insuranceList ){
if(iList.IAR_Start_Date__c != null){
insList1.put(iList, iList.IAR_Start_Date__c);
}
}
//Query the number of insurance records for the corresponding projects
Map<Id,Milestone1_Project__c> is = new Map<Id,Milestone1_Project__c>([SELECT Id, Cleantech_Reference__c,
(SELECT Id, Project__c, Name FROM Insurance__r)
FROM Milestone1_Project__c WHERE Id in :projectIds]);
system.debug(is.size());
Map<Id, Integer> newMap = new Map<Id, Integer>();
for(Insurance__c i : insuranceList){
//if there is no insurance record associated with the project and if the newMap is empty
if(is.get(i.Project__c).Insurance__r.isEmpty() && !newMap.containskey(i.Project__c)){
Integer count = 1;
i.Name = is.get(i.Project__c).Cleantech_Reference__c+'/'+'INS-'+string.valueOf(count);
newMap.put(i.Project__c, count);
}
//if there are insurance records and the newMap is empty
else if(!is.get(i.Project__c).Insurance__r.isEmpty()&& !newMap.containskey(i.Project__c) )
{
Integer count = is.get(i.Project__c).Insurance__r.size()+1;
i.Name = is.get(i.Project__c).Cleantech_Reference__c+'/'+'INS-'+string.valueOf(count);
newMap.put(i.Project__c, count);
}
//if the newMap is not empty
else{
Integer count = newMap.get(i.Project__c)+1;
i.Name = is.get(i.Project__c).Cleantech_Reference__c+'/'+'INS-'+string.valueOf(count);
newMap.put(i.Project__c, count);
}
}
}
}