1

Here is my query:

List<object1__c> lstRecords = [SELECT field1__c, field2__r.Name FROM Object1__c];
populateData((List<sObject>)lstRecords);

//I need to pass sObject, since this function would be used for multiple objects
public void populateData(List<sObject> lstRecords){
    System.debug(lstRecords[0].get(field1__c))         //This works fine
    System.debug(lstRecords[0].get(field2__r.Name))    //This does not work
}

The query debug shows following:

Object1__c:{field1__c=data}    //I don't see the field

Any solution for the above?

3

You should use

System.debug(lstRecords[0].getSobject('field2__r').get('Name'));

Because get() method in sObject class doesn't support reference field retrival. Relationship name to be used instead of field Name in the getSobject method.

You can refer this Stackexchange question for more information and the various get methods available for the SObject class.

Hope it helps.

1
  • Thanks @KeithC for adding the reference to SObject class. I was about to add that. – Vigneshwaran G Jul 9 '15 at 13:16
2

Actually the problem is Salesforce Sobject method get retrieves you the information from a record if it is a well formed column/field in the object.

Try using this in your second debug

getSobject('ParentRelationshipName');

List<Sobject> lstRecords = [SELECT AccountId, Account.Name FROM Contact Where AccountId !=null Limit 1];
System.debug(lstRecords[0].get('AccountId'));         
System.debug(lstRecords[0].getSobject('Account'));

18:42:57.035 (35456209)|EXECUTION_STARTED 18:42:57.035 (35488472)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex 18:42:57.046 (46363313)|USER_DEBUG|[2]|DEBUG|00190000010kcO0AAI 18:42:57.046 (46522790)|USER_DEBUG|[3]|DEBUG|Account:{Id=00190000010kcO0AAI, Name=Acc1} 18:42:57.046 (46597800)|CODE_UNIT_FINISHED|execute_anonymous_apex 18:42:57.047 (47922463)|EXECUTION_FINISHED

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.