1

I am trying to get values from my object which have Contact as Look up field. But when I am trying to get value of Fields from Contact Object using relation I am unable to get any result.

EX:

List<SponsorTracking__c> stObj = [SELECT Id, Contact__r.MailingCountry , Contact__r.LastName , 
Contact__r.Name , Contact__r.MailingState , Contact__r.MailingCity , Contact__r.Account.Name , 
Contact__r.Title , Contact__r.FirstName , Contact__r.Email  ,Contact__c,Account__c,CustomerInfo__c FROM 
SponsorTracking__c WHERE Contact__c IN : cnTset]

stObj.get('Contact__r.Title') is not returning any value even no exception is being thrown.

Contact__c is Lookup to Contact Object

I tried stObj.get('Contact__r') and the get('Title') on returned Object.

Please let me know what i am missing here to get Contact__r.Title value.

Thanks

0

2 Answers 2

4

When you are retrieving a reference to an SObject from an SObject of unknown type you need to use the (poorly documented) getSObject method:

List<SObject> sobs = ...;
for (SObject s : sobs) {
    SObject c = s.getSObject('Contact__r');
    String t = (String) c.get('Title');
    ...
}

But as mrBlaQ correctly points out in this case the SObject type is known to the compiler so a direct reference (rather than references keyed by strings) can be used:

List<SponsorTracking__c> sobs = ...;
for (SponsorTracking__c s : sobs) {
    String t = s.Contact__r.Title;
    ...
}
2
  • 1
    I don't see a need for getSObject here. Can't you just refer to s.Contact__r.Title Inside the for() ? Sep 18, 2014 at 19:40
  • @mrBlaQ You are right as in this case the type SponsorTracking__c is known. I'll update the answer.
    – Keith C
    Sep 18, 2014 at 19:43
0

I don't think you're using stObj.get() properly here. get() on a List object only supports integers. You'd do something like stObj.get(0).Contact__r.Title; for the first record returned from that query. Or, use the iterative method described by Keith.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .