2

How can I get the field results from a dynamic database query to be available to be put into a list? Here is the code I have:

//Query on the destinationObjectFieldName results
    List<sObject> desinationObjectList =
        Database.query('SELECT Id, Name FROM ' + destinationObject + 'WHERE Id IN :relJunctionObjects' );
    System.debug('desinationObjectList List contains: ' + desinationObjectList);

    //Add the results into the RelatedObject list
    for(sObject s: desinationObjectList) {
        pickListValuesList.add(new RelatedObject(s.Id,s.Name));
    }

Yet I get the error

Variable does not exist: Name

1 Answer 1

9

The only field you can directly retrieve from an sObject is Id. All other fields must be referenced dynamically:

    pickListValuesList.add(new RelatedObject(s.Id,(String)s.get('Name')));

This is due to the fact that the compiler must be able to verify that the field exists, which it cannot do for Name without a concrete sObject type (e.g. Account). Note that a few objects do not have a Name field, so if you use this code on some specific objects, expect a QueryException.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.