+ Start a Discussion
viktorVviktorV 

before insert trigger - referenced details

I'd like to create a before insert trigger for contacts, which copies some details from the referenced account. My problem is, that I can get the AccountId, but the Account.field values are null.

An example code:

 

trigger account_details  on Contact (before insert) {
 for(Contact t: trigger.new){
  t.Custom_detail__c = t.Account.Custom_detail_on Account__c;
 }
}

Contact custom detail will be null, even it has value on referenced Account.

Is there a kind of simple solution or I should get the Account details with SOQL?

 

Thank you,

Viktor

 

 

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

In a before / after Insert trigger, you are not able to use relationship references, because for reasons of optimization and efficiency, those relationships fields have not been loaded in memory.

 

SO you'll have to select the Account records, rather than use relationship references.

 

Id[] accIds = new Id[]{};

 

for (Contact c : trigger.new)

accIds.add(c.AccountId);

 

for(Account acc : [Select Id, Custom_Detail__c from Account where Id in :accIds])

{

All Answers

Ritesh AswaneyRitesh Aswaney

In a before / after Insert trigger, you are not able to use relationship references, because for reasons of optimization and efficiency, those relationships fields have not been loaded in memory.

 

SO you'll have to select the Account records, rather than use relationship references.

 

Id[] accIds = new Id[]{};

 

for (Contact c : trigger.new)

accIds.add(c.AccountId);

 

for(Account acc : [Select Id, Custom_Detail__c from Account where Id in :accIds])

{

This was selected as the best answer
viktorVviktorV

Thank you, Ritesh!