How do I get a list of fields in a shared sObject?

I am trying to build a query builder where the sObject result can contain an indefinite number of fields. I am using the result to build a dynamic table, but cannot find a way to read the sObject for the list of fields that were in the query.

I know how to get a list of ALL fields using getDescribe information, but the request may not contain all of these fields.

Is there a way to do this?


source to share

4 answers

Presumably you are building the query as a string, since it is dynamic, so you cannot just loop through the fields in the descriptive information and then use .contains()

in the query string to see if it was requested? Not crazy elegant, but seems to be the easiest solution here.

Taking this, perhaps you have a list of fields selected in a list of strings or similar and can you just use that list?



Not sure if this is exactly what you were looking for, but something like this?

public  list<sObject>       Querylist               {get; set;}


Define a search string

string QueryString = 'select field1__c, field2__c from Object where';


Add as many as you need to build the search if the user searches in these fields

if(searchParameter.field1__c != null && searchParameter.field1__c != '')
        QueryString += ' field1__c like \'' + searchParameter.field1__c + '%\' and ';

if(searchParameter.field2__c != null && searchParameter.field2__c != '')
        QueryString += ' field2__c like \'' + searchParameter.field2__c + '%\' and ';


Delete the latter and

QueryString = QueryString.substring(0, (QueryString.length()-4));
      QueryString += ' limit 200';


add request to list

for(Object sObject : database.query(QueryString))




To get a list of fields in sObject, you can use a method like:

public Set<String> getFields(sObject sobj) {
    Set<String> fieldSet = new Set<String>();
    for (String field : sobj.getSobjectType().getDescribe().fields.getMap().keySet()) {
        try {
        } catch (Exception e) {
    return fieldSet;


You should refactor this approach for your context, but it works. Just go to sObject and it will return you a list of field names.



I suggest using a list of fields to create a query and table. You can put a list of fields in the result so that it is available to everyone who uses it. Then you can build the table using result.getFields () and get the data using result.getRows ().

for (sObject obj : result.getRows()) {
    for (String fieldName : result.getFields()) { 


If you are trying to work with a query that is out of your control, you will have to parse the query to get a list of fields. But I would not suggest trying this. This complicates the code in a way that is difficult to execute.



All Articles