function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
random_duderandom_dude 

Dynamic Insert possible? Fieldname in a variable

I need to do something pretty simple: adding contacts to the existing salesforce contacts like so:

 

Contact[] allContacts = [select firstName, lastName, Email, Birthdate, description from contact];
Contact newContact = new Contact(firstName = 'AAA', lastName='BBB', email='A@A.com' etc..);
allContacts.add(newContact);
upsert allContacts;

 

Problem is that the fields  "firstName, lastName, Email, Birthdate, description" are not fixed.  They will change depending on who uses the application. 

 

Is there a way to use string variables instead of fieldnames to add a new contact?

 

Something along the lines of:

String field1 = 'first_name';

newContact.Fields[field1] = 'AAA';

Best Answer chosen by Admin (Salesforce Developers) 
aalbertaalbert

Yes, here is the documentation on dynamic dml in apex.

The syntax is similar to:

 

sObj.put('Name','test Account name');

 

 

 

All Answers

aalbertaalbert

Yes, here is the documentation on dynamic dml in apex.

The syntax is similar to:

 

sObj.put('Name','test Account name');

 

 

 

This was selected as the best answer
random_duderandom_dude

oooh.. Thanks! :smileyhappy: