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
Robert_S_HarperRobert_S_Harper 

Referencing a runtime field.

What I'd like to do is something like the follwoing:

public List<String> foo( String objectName, String fieldName, String searchString ){
List<String> returnValues = new List<String>();
String qs = 'SELECT ' + fieldName + ' FROM ' + objectName + ' WHERE ' + fieldName + ' LIKE \'%' + searchString + '%\'';
List<sObject> records = Database.query( qs );
for( sObject rec : records )
    returnValues.add( rec.get( fieldName ) );
}

 The poblem is that I can't figure out how to get the value for the rec.sObjectField object.

 

Is there a way to do this? I can't seem to find it in the Apex documentation.

 

Thanks in advance.

Best Answer chosen by Admin (Salesforce Developers) 
Robert_S_HarperRobert_S_Harper

I was recieving a compile error on the line where I was attempting to add the value of the field to the list. I found by testing that all I had to do was to cast the field to a String and it seemed to work. At least in some test code where I logged out the value returned.

 

Something like:

returnValues.add( (String)rec.get( fieldName ) );

 If I run into troubles with this, I'll re post what those are.

All Answers

Bhawani SharmaBhawani Sharma
Your methods looks absolutely correct. Can you please explain your question in bit more detail?
Robert_S_HarperRobert_S_Harper

I was recieving a compile error on the line where I was attempting to add the value of the field to the list. I found by testing that all I had to do was to cast the field to a String and it seemed to work. At least in some test code where I logged out the value returned.

 

Something like:

returnValues.add( (String)rec.get( fieldName ) );

 If I run into troubles with this, I'll re post what those are.

This was selected as the best answer