+ Start a Discussion
Sainath VenkatSainath Venkat 

auto number trigger failing if existing records are having field as null

I am working on trigger which will populate a number field based on parent record.

For each parent record, child will have auto number

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
1) Actionitem1
2) Actionitem2
3) Actionitem3
4) Actionitem4

I tried below code which is not working if there are child existing records where auto numberfield is null rest everything is working perfectly.

my code is below, can anyone help me out in this issue.
public class RenameActionItem {
    public static void renameActionItemRecord(List<Action_Item__c> actionItemList){
            //Set to store the buildcycleid from action item
            Set<Id> buildCycleId = new Set<Id>();
            for(Action_Item__c actionObj : actionItemList) {
            //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){
                //if existing records have DCS_Auto_Number__c == null then setting it to 1 using custom label
                integer length = integer.valueOf(Label.Auto_Number);
                    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){
                            cObj.DCS_Auto_Number__c = length;
       }catch(Exception e){
            System.debug('Exception in code'+e.getCause() + 'Exception in Line number'+e.getLineNumber());

Best Answer chosen by Sainath Venkat
Boss CoffeeBoss Coffee
What type of field is DCS_Auto_Number__c? Is it an Integer field?

You could try changing the try catch to the following to handle null.
if(bObj.Action_Items__r[0].DCS_Auto_Number__c != null) {
   length = integer.valueOf(bObj.Action_Items__r[0].DCS_Auto_Number__c);