[SalesForce] Why is this Apex Trigger throwing a Null Pointer Exception: Argument cannot be null

This trigger references blank fields, and complex formula fields. The reason I'm trying to do a trigger and not a formula is that it resolves to too many characters because of referenced formula fields that reference formula fields…

Some of the fields used here reference fields on the parent object (Opportunity), do I need to SELECT all the fields used by all the formulas in order for it work?

This is the first trigger I've ever tried to write, so if I'm missing something basic feel free to point that out. 🙂

Trigger kaPaymentTermsFormulaTLTFinalPayment on PaymentTerms__c (before update) {
    for(PaymentTerms__c record : [SELECT HowtotreatPPI__c, FinalPaymentModification__c, PPIAmount__c, TLTPayment__c 
                                  FROM PaymentTerms__c 
                                  WHERE Id IN :Trigger.newMap.keyset()
                                  ])
        if (record.HowtotreatPPI__c =='Pay up front out of pocket'){
              Trigger.newMap.get(record.Id).TLTFinalPaymentTest__c = record.FinalPaymentModification__c + record.PPIAmount__c + record.TLTPayment__c; 
        } else {
              record.TLTFinalPaymentTest__c = record.PPIAmount__c + record.TLTPayment__c;
    }

}

And this is the error I'm getting:

Error: Invalid Data. Review all error messages below to correct your
data. Apex trigger kaPaymentTermsFormulaTLTFinalPayment caused an
unexpected exception, contact your administrator:
kaPaymentTermsFormulaTLTFinalPayment: execution of BeforeUpdate caused
by: System.NullPointerException: Argument cannot be null.:
Trigger.kaPaymentTermsFormulaTLTFinalPayment: line 6, column 1

Most of the fields referenced are Currency fields, but FinalPaymentModification__c is a roll-up summary from another custom object. It didn't seem to be a problem until I tried System.assertNotEquals(Null, record.FinalPaymentModification__c); and then in the developer console it says Variable does not exist for that field.

It actually says that for TLTPayment and PPIAmount too, basically all fields but the picklist are currently blank. If I was in Formula editor I would check "treat blank fields as zeroes", where can I do that in a trigger?

UPDATE

I tried the trigger with fields that I knew to have values in them, and it worked, as long as I added () around the fields after 'Trigger.newMap.get(record.Id).TLTFinalPaymentTest__c = '

But adding () around the fields I need to use doesn't work, because they are blank.

I also tried creating a Workflow Rule to do the same thing, and THAT threw an error of > Division by zero
Turns out that a formula referenced by a formula referenced by TLTPayment__c includes a division by a field that is blank.

Best Answer

Try using System.assertnotEquals(null, .. .... ..) function before the for loop. Check if that helps !

Related Topic