+ Start a Discussion
Ken KoellnerKen Koellner 

Dynamically reference and set sObject fields.

I know how to write dynamic sSoql in Apex where I can control the select list with code.


What I want to do is dynmically set certain fields in an sObject before I save it.  I'll have the names of the fields in variables.


Anyone know if there's a way to set a field in an sObject where the field name is set dynamically. 


I want to do something like--


  mySObject.setField('FieldName', 'NewValue');



Ken KoellnerKen Koellner

I think I might have found the answer.  I see that sObject as a put(fieldname,newvalue) and get(fieldname) methods.



Ankit AroraAnkit Arora

Here is the code :


sObject sObj = Schema.getGlobalDescribe().get('Account').newSObject() ;  
                sObj.put('name' , 'Test Account Name') ;  
                insert sObj ;


For more info how to work with sObjects please visit :




And for more info on sObject methods :





Ankit Arora

Blog | Facebook | Blog Page

Jason Kuzmak 12Jason Kuzmak 12
@Ken Koellner This really helped! Glad you figured it out.