update a records using generic fields

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, '[email protected]'); // your constant here
    }
}

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


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('Birthdate', System.today());
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;

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');

  }
}

Tags:

Apex