Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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

3 Answers 3

up vote 7 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, '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'};

share|improve this answer
1  
exactly what i wanted.. You are god –  Prady Nov 8 '12 at 10:18

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;
share|improve this answer

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

 
discard

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.