+ Start a Discussion
Jake GmerekJake Gmerek 

Trigger update issue

Hello I have three objects Order__c, Serial_number__c and path__c

 

Serial Number has a look up on order and is the master of path.  Path has a lookup on order.

 

Before inserting a path record I am trying to automatically get the order field filled in by using the serial number.  Here is my trigger:

 

 

trigger addOrder on Path__c (before insert) {
     
     for (integer i = 0; i < trigger.new.size(); i++){
    
        trigger.new[i].order__c = trigger.new[i].serial_number__r.Order__r.id;
         
    }
}
It does not return an error, but just leaves the Lookup field on Path blank.  Any Ideas on why this is not working?
Thanks

 

Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

In a before insert trigger, __r relationship references will evaluate to null. 

 

You will therefore need to query for the SerialNumbers before setting the reference

 

 

trigger addOrder on Path__c (before insert) {
     
     Id[] serialNumIds = new Id[]{};
     for(Path__c path : trigger.new)
        serialNumIds.add(path.Serial_Number__c);
Map<Id, Serial_number__c> idSerialMap = new Map<Id, Serial_number__c>([Select Id, Order__c from Serial_Number__c where Id in :serialNumIds]);
for(Path__c path : trigger.new)
path.Order__c = idSerialMap.get(path.Serial_Number__c).Order__c;
}

 

I wrote a little blog post explaining this http://cloudnow.wordpress.com/2011/04/04/apex-bloopers-why-art-thou-null/

 

All Answers

Ritesh AswaneyRitesh Aswaney

In a before insert trigger, __r relationship references will evaluate to null. 

 

You will therefore need to query for the SerialNumbers before setting the reference

 

 

trigger addOrder on Path__c (before insert) {
     
     Id[] serialNumIds = new Id[]{};
     for(Path__c path : trigger.new)
        serialNumIds.add(path.Serial_Number__c);
Map<Id, Serial_number__c> idSerialMap = new Map<Id, Serial_number__c>([Select Id, Order__c from Serial_Number__c where Id in :serialNumIds]);
for(Path__c path : trigger.new)
path.Order__c = idSerialMap.get(path.Serial_Number__c).Order__c;
}

 

I wrote a little blog post explaining this http://cloudnow.wordpress.com/2011/04/04/apex-bloopers-why-art-thou-null/

 

This was selected as the best answer
Jake GmerekJake Gmerek

Good Deal, Thanks I got it now