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
Adam NilaAdam Nila 

Apex Specialist Superbadge - Null Product Life Span Months

Requirement: Another aspect about parts is they all have different lifespans. Therefore, you need to calculate and set the next service due date to the end of the maintenance cycle defined on the related equipment record.

Relevant Code:
Public Static List<Product2> prodCodes = [SELECT Id, productCode, lifespan_months__c FROM Product2];

Public Static Decimal prodExpiration; 

for(Product2 prod : prodCodes){
                    
                    if(newCase.Product__c == prod.productCode){
                        system.debug(newCase.Product__c);
                    	system.debug(prod.productCode);
                        prodExpiration = prod.lifespan_Months__c;
                        system.debug(prodExpiration);
                        system.debug(prod.Lifespan_Months__c);
                    }
                }

                //This line is throwing a null pointer error according to salesforce
                Decimal daysTilDue = prodExpiration * 30;

                Date_Due__c = date.today()+ daysTilDue.intValue(),

The system debug confirms that it finds matching Product codes, but shows both prodExpiration and prod.lifespan_months__c as being null.  Should the direct field reference show up at a minimum?  And is there a better way to go about this?
 
Best Answer chosen by Adam Nila
Jeff DouglasJeff Douglas
Adam,

The Due Date should be someting like:
 
myAwesomeCase.Date_Due__c = System.today().addDays(Integer.valueOf(c.Equipment__r.Maintenance_Cycle__c));

HTH

Jeff Douglas
Trailhead Developer Advocate

 

All Answers

Hargobind_SinghHargobind_Singh
Hi, the numeric fields will have a null stored unless there is a value in it. Even zero is not assumed. 
When assigning the variable, you should check for null and assign zero if that is your default value, e.g.:
 
Decimal varName = (Obj.FieldName__c !=null)?Obj.FieldName__c:0;


 
Jeff DouglasJeff Douglas
Adam,

The Due Date should be someting like:
 
myAwesomeCase.Date_Due__c = System.today().addDays(Integer.valueOf(c.Equipment__r.Maintenance_Cycle__c));

HTH

Jeff Douglas
Trailhead Developer Advocate

 
This was selected as the best answer