Find your content:

Search form

You are here

update a records using generic fields

 
Share

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?


Attribution to: Prady

Possible Suggestion/Solution #1

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, 'example@example.com'); // your constant here
    }
}

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


Attribution to: eyescream

Possible Suggestion/Solution #2

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

  }
}

Attribution to: Mohith Shrivastava

Possible Suggestion/Solution #3

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 to: Andrew Fawcett
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4193

My Block Status

My Block Content