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
johncusackjrjohncusackjr 

SOQL Retrieving CreatedBy.Name Field?

Hi,

 

In one of my controller classes I need to retrieve Created By Name field from a custom object.

 

I am running

 

String queryString = 'Select id, File_Name__c, CreatedById, CreatedBy.Name, CreatedDate from ...';

 

Querying the custom object and putting fields in a list:

 

List<SObject> myList = Database.query(queryString);

 

Then trying to set the created by name to a wrapper class field in a loop over myList:

 

w.setCreatedByName((String)f.get('CreatedBy.Name'));

 

But it is giving me

 

Invalid field CreatedBy.Name for XYZ__c

 

What might be the problem. How can I retrieve CreatedBy.Name. I can retrieve CreatedById directly but it is not solving my problem.

 

Thanks...

FaridKognozFaridKognoz

Hi;

I don't think you can use the "." when getting a field value ( f.get('CreatedBy.Name')); What you could do if you still want to use the "get" is:

 - fetching the record as you are doing

 - User u =  f.createdBy;

 - String name = (String) u.get('Name');

 

Don't know if that helps...

johncusackjrjohncusackjr

Unfortunetly it didn't work.

 

User u = (User)f.get('CreatedBy');

w.setCreatedByName((String)u.get('Name')); also didn't work.

 

Gave this error:

Save error: Incompatible types since an instance of Object is never an instance of SOBJECT:User

 

Any other suggestions? Thanks...

Message Edited by johncusackjr on 11-19-2009 06:48 AM
FaridKognozFaridKognoz

I don't think you can retrieve an Sobject with the "get" function. That's why (User) f.get('CreatedBy') doesn't work. What you can retrieve with get are Primitive Types.

 

 

gayatri sfdcgayatri sfdc
Hi john,

I am not sure at that  time, it would retrieve or not, but  now it will definitely work. Please see below code ( for future users)

public class Sample{  
    list<wrapper_cls> wrplst = new list<wrapper_cls>();
    public void Testmtd(){
        String field = 'Eduardo A. Kirchner';
        String queryString = 'SELECT id,name from Renewal_Request__c where CreatedBy.name =\''+   String.escapeSingleQuotes(field)+'\'limit 5';
        
        List<Renewal_Request__c> myList = Database.query(queryString);
        system.debug('##########'+myList);
        
        for(Renewal_Request__c  r : myList){  
            wrplst.add(r.name);
               // system.debug('*****'+ nameHolder); 
        }
    }    
      public  class  wrapper_cls{
        public  String  nameHolder {get;set;} 
        public wrapper_cls( String nmehold){
         nameHolder= nmehold;
        }  
   }
}

Keep Learning:)