Apologies if this was already answered, but I didn't see a clear cut solution for this issue in Salesforce. I want to be able to dynamically set values for a record based on a predefined list of strings. However having some trouble on where to start...

Lead soqledLead = [select id, Name, Age__c,LastName,Company FROM Lead where Id = '00Q0y00001XeivU'];
Lead singleLead = new Lead();
List<String> listOfFieldsViaAPIname = new list<String> { 'Name','Age__c', 'LastName', 'Company'  };

for(String s : listOfFieldsViaAPIname){
    system.debug('API Name ====>' +s);
    singleLead.s = soqledLead.s;
    //^this will obviously fail (Variable does not exist: s)

It's just a matter using the right functions, namely get and put, from the sObject class.

for(String s : listOfFieldsViaAPIname){
    singleLead.put(s, soqledLead.get(s)); 

Could also stand to make your query use your fields, could also make those fields into a fieldset, but thats out of scope of this question.

  • 1
    PERFECT!!! I've never utilized get/put like that. And actually yes I have all of those fields in a fieldSet, just wanted to simplify the question for this post. – rmarq423 Jan 16 '18 at 18:30
  • 1
    Any sObject (Most Salesforce standard objects, plus custom objects) will have these methods exposed- very useful to write code which doesn't have to care about the values, fields or types of the data its working with. I'll always add little blurbs like that, mostly for future users, or in case OP (you) is newish to the platform. Very nice to write code which performs some basic operation off of a list of fields which you can modify on production without needing to make code changes. – battery.cord Jan 16 '18 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.