+ 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 :

 

http://forceguru.blogspot.com/2011/08/inserting-sobject-dynamically-in.html

 

And for more info on sObject methods :

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_sobject.htm

 

Thanks

Ankit Arora

Blog | Facebook | Blog Page

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