I'm new to apex and still trying to figure things out. I'm attempting to pull the Parent data from the Child to then update. I keep receiving the error "Variable does not exist: Location__r".
Please not the custom object singular is "Locations" and the field of opportunity is "Location".
public class OpportunityTriggerHandler {
//Setting list of opportunities IDs
public static void opptoAcctModifier(Set<ID>oppsIds)
{
//Create list of locations to update
List<Locations__c> modifiedLocs = new List<Locations__c>();
//Grabbing Opportunity and Related Locations fields
for(Opportunity opp : [SELECT Id,Location__c,Locations__r.Status__c,Locations__r.Original_Payment_Amount__c,Locations__r.Date_Payment_Processed__c,Locations__r.Date_Payment_Received__c FROM Opportunity WHERE Id IN :oppsIds])
{
//Locations fields to update and Opportunity fields to pull from
opp.Locations__r.Original_Payment_Amount__c = opp.Amount;
opp.Locations__r.Date_Payment_Processed__c = opp.CloseDate;
opp.Locations__r.Date_Payment_Received__c = opp.CloseDate;
opp.Locations__r.Status__C = opp.Billing_Status__c;
modifiedLocs.add(opp.Location__c);
}
System.debug(modifiedLocs);
//update modifiedLocs;
}
}
Best Answer
There are a few things wrong in your provided code, but it should be pretty easy to fix.
Before we get to that though, some brief explanation.
__c
(for custom relationships) orId
(e.g.AccountId
a "standard" relationship on the Opportunity object) contain the Id of the related record__r
for custom relationships and dropping the "Id" (e.g.Account
instead ofAccountId
on Opportunity) for most standard relationshipsWith that out of the way, let's fix your code
Querying for parent fields in order to update them seems a little strange to me though. It would certainly work, but querying for the parent fields is unnecessary.
Given that this is code that appears to be run as part of a trigger, the entire query is not strictly required either. The limit of 100 queries per (synchronous) transaction is the most common one people run into, so anything we can do to reduce queries is worth considering.
If I were to write this method, I'd make use of the trigger context variables (passed in as a List to the method) and our ability to use the SObject constructor to set a record Id (which allows us to update a record without querying for it)