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
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.