1
Expense__c expenses = [select Owner.Name, Contact__r.Name, from Expense__c];

for (Expense__c i : expenses)
{   
    String expOwner = String.valueOf(i.get('Owner.Name'));
    String contact = String.valueOf(i.get('Contact__r.Name'));
}

I get following error: Invalid field Owner.Name for Expense__c

How do I retrieve values of Owner Name and Contact Name?

4

With static SOQL (where the SObject structure is known at compile-time) you can do it like this:

Expense__c expenses = [select Owner.Name, Contact__r.Name, from Expense__c];

for (Expense__c e : expenses)
{   
    String expOwner = e.Owner.Name;
    String contact = e.Contact__r != null ? e.Contact__r.Name : null;
}

Note if some relationships are optional you need to check for nulls to avoid NullPointerExceptions in your code.

If using dynamic SOQL you need to use getSObject first then get.

| improve this answer | |
2

If the expense is the child in a master-detail relationship there will be no "Owner" field available as it is owned by the parent

As an aside, it would be helpful when asking questions if you posters would specify the line where the error is occurring or when it is occurring (compile vs runtime). There are two possible places where that message could occur.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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