+ Start a Discussion
dwickdwick 

Basic trigger help

Hi,

 

I'm attempting to update a field after insert based on a simple calculation between to objects with a master-detail retationship.  I was under the impression I could not use a forumla for this, but feel free to correct me.

 

Here's the code:

 

 

trigger ComputeTotalSamples on Jobs__c (after insert) {
        for(Jobs__c j: trigger.new) {
            j.TotalSamples__c = j.BatchCount__c * j.ProtocolName__r.BatchSize__c;
            update j;
        }
}

 and the error:

 

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

 

Any help would be greatly appreciated.

 

Dave

 

Best Answer chosen by Admin (Salesforce Developers) 
SuperfellSuperfell

The object passed in the trigger context only contains data for that object, its doesn't automatically populate all the related objects, and you're trying to reference a related object (via the protocolName__r relationship).

 

If Jobs__c is a detail record in a master/detail with protocolName as the master, then you should be able to do this with a formula field. 

All Answers

SuperfellSuperfell

The object passed in the trigger context only contains data for that object, its doesn't automatically populate all the related objects, and you're trying to reference a related object (via the protocolName__r relationship).

 

If Jobs__c is a detail record in a master/detail with protocolName as the master, then you should be able to do this with a formula field. 

This was selected as the best answer
dwickdwick

I was able to get the formula working, thank you!  For the sake of learning, in order to get the data for both objects would i have to use soql?

SuperfellSuperfell

Yes, you'd have to use SOQL to query the related object. You'd also have to work out how to stop the recursive trigger, your trigger would cause your trigger to fire again, and so on in a loop.