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
JJE_OLDJJE_OLD 

Getting field value dynamically

Hi,

 

I'm looking for a way to access an object field dynamically (i.e. with the field name contained in a variable)

 

If I have:

 

String FieldName = 'AccountNumber';
Account ac = [SELECT id, Name, AccountNumber FROM Account LIMIT 1];

I'm trying to do something like this:

Result = ac[FieldName];

Where Result is the Value contained in the AccountNumber Field.

 

Is there a way to do this in apex?

 

thanks.

Best Answer chosen by Admin (Salesforce Developers) 
Navatar_DbSupNavatar_DbSup

Hi,
You can use the follow method for retrieving the field values using dynamic apex

 

SObject s = [SELECT accountNumber FROM account LIMIT 1];
Object o = s.get('AccountNumber');

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.