In my trigger on Opportunity I am trying to access name field of contract on opportunities from newMap by opportunity.Contract.Name(There is a standard lookup Opportunity.ContractId). It returns null to me, but i know that it's not. May be it is because i can't access fields in a such way? I really don't want to use SOQL query here, any chance i can avoid it?
1 Answer
Parent and child relationships are not populated in the Trigger.new
, Trigger.newMap
, Trigger.old
, and Trigger.oldMap
properties. You only get the fields on the record itself, including any formulas. If you really wanted to avoid the query, you could use a formula field:
Contract Account Name (Contract_Name__c) (Text)
Contract.Name
Which you could use in your trigger:
for(Opportunity record: Trigger.new) {
String accountName = record.Contract_Name__c;
// ...
}
Aside from that, you do need to query parent/child records to gain access to that data. This is usually done in an Aggregate-Query-Update pattern:
Map<Id, Contract> contracts = new Map<Id, Contract>();
// Aggregate
for(Opportunity record: Trigger.new) {
contracts.put(record.ContractId, null);
}
// Query
contracts.putAll([SELECT Name FROM Contract WHERE Id = :contracts.keySet()]);
// Update
for(Opportunity record: Trigger.new) {
String contractName = contracts.get(record.ContractId);
// ... do stuff here
}