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
AlaaAlaa 

accessing Account object inside a trigger on opportunity

Hi , I have a trigger on opportunities after update, in the trigger am trying to get the Account object as follow:

 

for (Opportunity o : Trigger.new) {
.

.

.
acc=o.Account;
.

.

.
}

 

but the acc object is always null while the oportunity am updating has parent acount, whats wrong?

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

You have to query for that data. Here's a typical example:

 

trigger X on Opportunity(before insert) {
  map<id,account> accounts = new map<id,account>();
  for(opportunity o:trigger.new) {
    accounts.put(o.accountid,null);
  }
  accounts.remove(null);
  accounts.putAll([select id,name,industry from account where id in :accounts.keyset()]);
  for(opportunity o:trigger.new) {
    if(accounts.containskey(o.accountid)) {
      o.related_account_name__c = accounts.get(o.accountid).name;
    }
  }
}

As a general rule, no related records are ever provided "by default"; you have to query the database to get at that information.

All Answers

sfdcfoxsfdcfox

You have to query for that data. Here's a typical example:

 

trigger X on Opportunity(before insert) {
  map<id,account> accounts = new map<id,account>();
  for(opportunity o:trigger.new) {
    accounts.put(o.accountid,null);
  }
  accounts.remove(null);
  accounts.putAll([select id,name,industry from account where id in :accounts.keyset()]);
  for(opportunity o:trigger.new) {
    if(accounts.containskey(o.accountid)) {
      o.related_account_name__c = accounts.get(o.accountid).name;
    }
  }
}

As a general rule, no related records are ever provided "by default"; you have to query the database to get at that information.

This was selected as the best answer
AlaaAlaa

Thanks. now its working.