Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to update some fields in an object from apex. The number of fields is not constant i.e. in some instances there might be 3 fields to be updated in some cases there could be 10.

I have these field names in a list of Strings that is generated dynamically.

Is there a way we could say

 contact.lstfieldname[0] = 'update value';

The above wouldn't work, is there a way we would mimic it?

share|improve this question
Great question. – martin Jul 7 '15 at 7:25
up vote 13 down vote accepted

2 loops: outer on your contacts, inner on your list of field names. And dynamic apex with get() and put(), like in this question: Less verbose dynamic +=?

List<String> fields = new List<String>{'FirstName', 'LastName', 'Email'};
List<Contact> contacts = [SELECT Id FROM Contact LIMIT 5];

for(Contact c : contacts){
    for(String fieldName : fields){
        c.put(fieldName, ''); // your constant here

Having this sample you can experiment further: Map<String, String> valuesToApply = new Map<String, String>{'FirstName' => 'John', 'LastName' => 'Doe'};

share|improve this answer
exactly what i wanted.. You are god – Prady Nov 8 '12 at 10:18
Great answer. Thanks. – martin Jul 7 '15 at 7:26

You can use the get and put methods on your object for this type of access. You can review the methods on the SObject base class (every standard and custom object supports these methods). Enjoy!

Contact contact = new Contact();
Map<String, Object> fieldValueMap = new Map<String, Object>();
fieldValueMap.put('Description', 'Some descriptipon');
fieldValueMap.put('Title', 'Some title');
fieldValueMap.put('FirstName', 'Andrew');
fieldValueMap.put('LastName', 'Fawcett');
fieldValueMap.put('MyCustomField__c', 'My Custom Field Value');
for(String fieldName : fieldValueMap.keySet())
    contact.put(fieldName, fieldValueMap.get(fieldName));
insert contact;
share|improve this answer
Thanks for this reference to sObject base class, the get() method is useful for dynamically retrieving a field value when the Field name is delivered by something like a Custom Setting. – AlwaysThinkin Jan 8 '15 at 20:49

Following is the snippet code .I assume we have list of contacts to update and lst string to consider .

for(contact con:lstcontoUpdate){

for(String str:FieldstoConsider){

  con.put(str,'update value');

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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