2

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 !

3

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

2

In trigger context you can reach only fields from processed object level. This means no relation fields are available. Although you can get those values in 3 ways - either use SOQL query, formula field or workflow.

SOQL will allow you get value in before context from parent record - but will also consume 1 from your query limit.

You can create formula field to display value from parent record, but even if opportunity field have to be editable formula may be useful. Formula will collect required value from parent record(which later can be used in trigger). BUT it is bit risky - you in some cases (parent change, set parent, before insert) you may not get right value. So if you want to go with formula best idea will be to move to after trigger.

Workflow is best answer for me - It is safe, easy to maintain for user. Only disadvantage I can think of is this additional update on opportunity record. So in my oppinion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.