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
MaxFrielMaxFriel 

Invalid field error when trying to follow through a lookup...

All,

I am hoping there is something dumb I am missing here.  This is a sample bit of code that illustrates the problem.  I am trying to look up variable fields based off of custom settings so I have to use the get method on SObject just using a c.Investigations__r.Additional_Medical_Device_Eval_Info__c, won't work.  So my question is why does the following code give an invalid field error and how can I get the value for that field out of the object using the get mehtod?

Complaint__c c = [Select Investigations__r.Additional_Medical_Device_Eval_Info__c FROM Complaint__c Limit 1];
System.debug(c.get('Investigations__r.Additional_Medical_Device_Eval_Info__c'));

 Thanks in advance for any help.  

Best Answer chosen by Admin (Salesforce Developers) 
Sean TanSean Tan

You can't get lookup child fields via the .get method directly. You need to use the getSObject method to get the child object then the get on the child object returned from that:

 

Like so:

Complaint__c c = [Select Investigations__r.Additional_Medical_Device_Eval_Info__c FROM Complaint__c Limit 1];
SObject childObject = c.getSObject('Investigations__r');

if (childObject != null)
{
	System.debug(childObject.get('Additional_Medical_Device_Eval_Info__c'));
}

 

 

All Answers

Sean TanSean Tan

You can't get lookup child fields via the .get method directly. You need to use the getSObject method to get the child object then the get on the child object returned from that:

 

Like so:

Complaint__c c = [Select Investigations__r.Additional_Medical_Device_Eval_Info__c FROM Complaint__c Limit 1];
SObject childObject = c.getSObject('Investigations__r');

if (childObject != null)
{
	System.debug(childObject.get('Additional_Medical_Device_Eval_Info__c'));
}

 

 

This was selected as the best answer
MaxFrielMaxFriel

Awesome, thanks so much, I can't believe I missed that getSObject method.