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?
Answer
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;
Attribution
Source : Link , Question Author : Prady , Answer Author : Andrew Fawcett