I am working on one trigger to auto name child records based on Parent Record.
I have two objects which are having lookup relationship.
1) Build_Cycle__c
2) Action_Item__c
Auto number is working fine on creation but on deleting my trigger is not working.
lets say for one build cycle I have 4 action items
BUILD CYCLE:1
1) Actionitem1
2) Actionitem2
3) Actionitem3
4) Actionitem4
now count is 4 and if I delete Actionitem3 and creates Actionitem5 then count should be 5 but count is coming 4 only, can anyone help me out in this issue here if possible.
public class RenameActionItem {
public static void renameActionItemRecord(List<Action_Item__c> actionItemList){
try{
integer length1 = actionItemList.size();
Set<Id> buildCycleId = new Set<Id>();
for(Action_Item__c actionObj : actionItemList) {
buildCycleId.add(actionObj.DCS_Build_Cycle__c);
}
List<Action_Item__c> actionItemList2 = new List<Action_Item__c>();
actionItemList2 = [SELECT Id FROM Action_Item__c WHERE DCS_Build_Cycle__r.Id IN :buildCycleId];
List<Build_Cycle__c> buildCycleList = new List<Build_Cycle__c>();
buildCycleList = [SELECT Name, (SELECT Id FROM Action_Items__r) FROM Build_Cycle__c WHERE Id IN: buildCycleId];
for(Build_Cycle__c bObj : buildCycleList){
Integer length2 = bObj.Action_Items__r.size();
for(Action_Item__c cObj : actionItemList){
if(bObj.Id == cObj.DCS_Build_Cycle__c){
if(length2 < length2+length1){
cObj.Auto_Number__c = length2;
}
length2++;
}
}
}
}catch(Exception e){
System.debug('Exception in code'+e.getCause() + 'Exception in Line number'+e.getLineNumber());
}
}
}
Trigger:
trigger Rename on Action_Item__c (before insert) {
if(trigger.isInsert && trigger.isBefore){
RenameActionItem.renameActionItemRecord(trigger.new);
}
}