function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Manish Kumar 61Manish Kumar 61 

Error accessing parent object fields in trigger

My code is
 
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

       }

For email field, I am getting Attempt to de-reference a null object: error on same line

How do I solve this?

 
Vijay NagarathinamVijay Nagarathinam

opp.Account.Account_Email__c = opp.Email__c; // This line is throwing error

Query the parent object then only you can access the parent fields. Without quering the parent object it is not possible to update the parent record.
SunidharSunidhar
set<Id> acc_id = new set<Id>();
for(opportunity opp : trigger.new) {
 acc_id.add(opp.accountId)
}

map<id, account> acc_list = [SELECT id, Account_Email__c FROM account WHERE id IN : acc_id];

for(opportunity opp ; trigger.new) {
 opp.Email__c = opp.get(opp.accountId).Account_Email__c;
}