I'm having a problem with my code because I need to get a list of records of a dynamic type, and that is working alright, but then I need to use some of the fields and can't reach them, giving me the error

Variable does not exist

Here is a sample of the code:

    String queryString = 'select Id, '+ camposMainObj.get(0) +', '+  
    camposMainObj.get(1)+', '+ camposMainObj.get(2) +', test__c from ' 
    +sObjName+ ' where Id = \''+recordId+'\'';

    List<sObject> obj = database.query(queryString);

    system.debug('sObjName ::::::::: '+obj);

    string listType = 'List<'+sObjName+'>';

    List<sObject> castRecords = (List<sObject>)Type.forName(listType).newInstance();



    ChartObject__c co = new ChartObject__c();
    co.Pai__c = castRecords[0].Id;
    co.PaiName__c = castRecords[0].Name;
    co.PaiEmail__c = castRecords[0].Email__c;
    co.PaiPhone__c = castRecords[0].Phone__c;

The variable sObjName contains the correct object type (in this case Pai__c).

Only the Id is recognized. The result query looks like this:

    (Pai__c:{Id=a070O00001uWD58QAG, Name=pai1, Phone__c=910987654, Email__c=pai1@mail.com, test__c=asdf}

So I can get every field from the query, but can only get the Id on the new object and it matches the queried one. The Name, Phone__c, Email__c, etc give me that error. I tried many solutions but can't seem to make it work.


Apex requires types to be known at compile time to directly reference fields.

But there are are get methods in the SObject class for this case where the field names can be used in string form:

List<sObject> objects = database.query(queryString);
for (sObject o : objects) {
    String name = (String) o.get(camposMainObj.get(0));
    String email = (String) o.get(camposMainObj.get(1));
    String phone = (String) o.get(camposMainObj.get(2));

but it is up to you to cast to the correct type as the return value of get is Object.

Your Answer

