function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dileep KatariDileep Katari 

This trigger code is giving Null Pointer Error. Please help fix it

Product_Purchase_Date__c, Product_Total_Warranty_Days__c, Product_Has_Extended_Warranty__c are the custom fields on Case object. I am trying to summarise them within a text and display on the 'Warranty_Summary__c '  field

Any help would be appreciated. Thank you!

trigger WarrantySummary on Case (before insert) {
    
    
    
    for(Case nCase : Trigger.new){
        //Setting up variable to use in the summary field
        String purchaseDate             = nCase.Product_Purchase_Date__c.format();
        String createdDate                 = DateTime.now().format();
        Integer totalNoOfWarrantyDays    = nCase.Product_Total_Warranty_Days__c.intValue();
        Decimal warrantyPercentage      = (100 * (nCase.Product_Purchase_Date__c.daysBetween(Date.today()) 
                                          / nCase.Product_Total_Warranty_Days__c)).setScale(2);
        Boolean hasExtendedWarranty     = nCase.Product_Has_Extended_Warranty__c;
        
        //Populating the summary field
        nCase.Warranty_Summary__c       = 'Product purchased on ' + purchaseDate + ' ' + 'and case created on ' + createdDate + '.\n' 
                                        + 'Warranty is for ' + totalNoOfWarrantyDays + ' ' + 'days and is ' + warrantyPercentage + 
                                        '% through its warrant period.\n' + 'Extended warranty: ' + hasExtendedWarranty + '/n' + 
                                        + 'Have a nice day!';
        
        
                                        
       }
}
Best Answer chosen by Dileep Katari
Shobit GuptaShobit Gupta
You might be getting value of purchaseDate as NULL because there may not be any value in nCase.Product_Purchase_Date__c.format().

Please check the debug for the value in purchaseDate and try to pouplate value in your data.

All Answers

Shobit GuptaShobit Gupta
On what line you are getting error (while debugging)? Could you please elaborate?
Dileep KatariDileep Katari
@Shobit Gupta : 

Error Message as below : 

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger WarrantySummary caused an unexpected exception, contact your administrator: WarrantySummary: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.WarrantySummary: line 7, column 1

Line - 
        String purchaseDate             = nCase.Product_Purchase_Date__c.format();
Shobit GuptaShobit Gupta
You might be getting value of purchaseDate as NULL because there may not be any value in nCase.Product_Purchase_Date__c.format().

Please check the debug for the value in purchaseDate and try to pouplate value in your data.
This was selected as the best answer