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


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.

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.