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
MukulMukul 

Getting field dynamically in Apex?

Hi all,

 

I have a query where i am getting the fieldname dynamically from a peice of code. Then i have a loop and i want to access that field's value. Its not letting me do that. 

 

Here is my code -

 

       String leadquery = 'select ' + fldName + ' from lead';
         List <Lead> leads = Database.Query(leadquery);
    for (Lead lead : leads) {


     Integer val_fld = Integer.valueOf(lead.fldName);

    // Do something

    }

 

It doesnt let me do lead.fldName bcause it says "Invalid field fldName for sObject lead." Can anyone tell me how can i do it dynamically?

 

Any help is much appreciated.

paul-lmipaul-lmi
is "fldName" an actual field in your org, or are you using that as an example?  custom fields should have __c appended to them.
RajanJasujaRajanJasuja

Change the name of your field string,If you have a field with the name of "fldName" in lead.

 

 

Try this,

 

    String leadquery = 'select ' + fieldsToSelect + ' from lead'; 
    List <Lead> leads = Database.Query(leadquery);
    for (Lead lead : leads) {


     Integer val_fld = Integer.valueOf(lead.fldName);

    // Do something

    }

 

But it looks like that you don't have a field "fld.Name" in lead.

 

So try this,

 

 

 

    String leadquery = 'select ' + fieldsToSelect + ' from lead'; 
    List <Lead> leads = Database.Query(leadquery);
    for (Lead lead : leads) {


     String val_fld = lead.Name;

    // Do something

    }

 

If it works fine, then problem is not with selection,You don't have field with "fld.Name" in lead