Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have the following query:

public List<My_Main_Object__c> data;

data = [Select My_Object__r.Id FROM My_Main_Object__c where id=:XXXX];

How can I pass the result of this query into a variable?

I'm trying the following

public String returnedId;

returnedId = data.My_Object__r.Id;

But I'm getting the following error:

Initial term of field expression must be a concrete SObject: LIST<DMDEV55__My_Main_Object__c> 

Can anyone tell me what the issue is here and how I can pass My_Object__r.Id into the returnedId variable??

Cheers

share|improve this question

3 Answers 3

up vote 3 down vote accepted

Your [Select My_Object__r.Id FROM My_Main_Object__c where id=:XXXX]; query returning a list of My_Main_Object__c object.

So you will have to do something like

 if(data.size() > 0 ){ 
 returnedId = data[0].My_Object__r.Id; 
}
share|improve this answer
    
Excellent!! Cheers man, worked a treat! –  Daft Aug 28 at 12:06
    
Thanks. Can you please mark it best answer? –  Pramod Kumar Aug 28 at 12:30

In your code data is a list. So the reference to data.My_Object__r.Id is not valid as My_Object__r.Id is an attribute of each element in the list, not the list itself. When you are querying for and the where clause is using Id = XXXX, you can typically just assign to a single instance of an sObject.

Also you are querying an value using a relationship where it is unnecessary. In a custom relationship, the following is always true. object.Related_Object__c == object.Related_Object__r.Id

But the querying for the second is more expensive. So I would suggest the following:

public My_Main_Object__c data;

try { 
  data = [Select My_Object__c FROM My_Main_Object__c where id=:XXXX];
} catch (QueryException) {
  data = new My_Main_Object__c();
  //or handle the possible exception in some other way
}

if (data.My_Object__c != null){
  returnedId = data.My_Object__c;
} 

In all other cases, the best practice in Apex would be to assign to list, as you were doing iterate over the list to access the data:

data = [Select My_Object__r.Id FROM My_Main_Object__c where XXXX];

for (My_Main_Object__c mo : data){
  returnedId = data.My_Object__c; 
  //or something else
}

Not treating a list as a list can be problematic.

share|improve this answer

You can access a field directly from the SOQL using a dot:

Id returnedId = [Select My_Object__r.Id 
                 From My_Main_Object__c 
                 Where id=:XXXX].My_Object__r.Id;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.