+ Start a Discussion
Sainath VenkatSainath Venkat 

generic apex class and trigger for auto number of child records for each parent record

I worked on one trigger which will auto populate number field of all child records that were related to a parent record, for each parent record, child records auto number will start from 1.

I did achieved with below apex class and trigger, can anyone help me out in writing a generic trigger on Sobject for below apex class and trigger.

Apex class:
public class RenameActionItem {
    //code by venkat for auto number on actionitem object for a build cycle
    public static void renameActionItemRecord(List<Action_Item__c> actionItemList){
        try{
            //Set to store the buildcycleid from action item
            Set<Id> buildCycleId = new Set<Id>();
            for(Action_Item__c actionObj : actionItemList) {
                buildCycleId.add(actionObj.DCS_Build_Cycle__c);   
            }  
            
            //Fetch action items that are related to buildcycleid
            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]; 
            
            //Fetching Action item records in descending order to catch the highest Auto Number
            List<Build_Cycle__c> buildCycleList = new List<Build_Cycle__c>();
            buildCycleList = [SELECT Name, (SELECT Id, DCS_Auto_Number__c FROM Action_Items__r order by DCS_Auto_Number__c desc limit 1) FROM Build_Cycle__c WHERE Id IN: buildCycleId];
            
            for(Build_Cycle__c bObj : buildCycleList){
                //custom label to assign first record to 1 if there are no existing records
                integer length = integer.valueOf(Label.Auto_Number);
               try{
                  //if auto number is not null for existing records then storing in inetger variable
               if(bObj.Action_Items__r[0].DCS_Auto_Number__c != null){
                    length = integer.valueOf(bObj.Action_Items__r[0].DCS_Auto_Number__c);
                    }
                }catch(exception e){
                }
                for(Action_Item__c cObj : actionItemList){
                    if(bObj.Id == cObj.DCS_Build_Cycle__c){
                            length++;
                            cObj.DCS_Auto_Number__c = length;
                    }
                }
                    
            }
       }catch(Exception e){
            System.debug('Exception in code'+e.getCause() + 'Exception in Line number'+e.getLineNumber());
       }
    }
}
trigger:
 
trigger ActionItemTrigger on Action_Item__c (before insert, after insert, after update, after delete, after undelete) {
    if(trigger.isInsert && trigger.isBefore){
        RenameActionItem.renameActionItemRecord(trigger.new);
    }
}