[SalesForce] Access parent object field in apex trigger

I'm posting a piece of before insert/ update trigger, it has to populate custom email field on Opportunity into Account's Email custom field.

I'm trying to do something like this:

For(Opportunity opp : trigger.new)
     { 
       If(!SetEmaiIDs.contains(opp.Email__c)) // checking if added email is already not present on some other account
       {
         opp.Account.Account_Email__c  = opp.Email__c; // This line is throwing error

       }

Seems like this line 'opp.Account.Account_Email__c' is not working
Can't we access account field like above , it is giving
Attempt to de-reference a null object: error on same line

Thanks !

Best Answer

Trigger.new or Trigger.old contains only Object information, not any relationship fields.

You could make the trigger to 'after insert, after update'

Then use

For(Opportunity opp : [SELECT Email__c, Account.Account_Email__c FROM Opportunity Where Id IN: trigger.new){
// your code
}

Btw, using before insert you can't update parent object fields with out using DML statements

So, you need to modify the program and update parent Accounts using DML

Related Topic