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
SalesForce DummySalesForce Dummy 

Access field name value based on string

This may be a simple yes or no question. I'm trying to update a field based on a string. Example.

 

//Create contact to update and set string to the email field.

Contact TestContact = new Contact(Id = '003121212121212');

string conField = 'Email';

 

//Update contact email field.

testContact.conField = 'test@email.com';

update testContact;

 

What I'm trying to do is access a field name for an object based on a string. Is this possible at all in APEX?

 

Best Answer chosen by Admin (Salesforce Developers) 
Starz26Starz26

You would do something like this maybe:

 

 

//Create contact to update and set string to the email field.

Contact TestContact = new Contact(Id = '003121212121212');

string conField = 'Email';

 

//Update contact email field.

testContact.put(conField,'test@email.com');

update testContact;

//To get the value of the field you would
String val = testContact.get(conEmail);

 

You may have to make the conEmail string all lowercase. Sometime a Map key allows for non-case sensitive as in the case of field names but I do not recall the exception off hand. So if using conEmail does not work try conEmail.toLowerCase()

All Answers

Starz26Starz26

You would do something like this maybe:

 

 

//Create contact to update and set string to the email field.

Contact TestContact = new Contact(Id = '003121212121212');

string conField = 'Email';

 

//Update contact email field.

testContact.put(conField,'test@email.com');

update testContact;

//To get the value of the field you would
String val = testContact.get(conEmail);

 

You may have to make the conEmail string all lowercase. Sometime a Map key allows for non-case sensitive as in the case of field names but I do not recall the exception off hand. So if using conEmail does not work try conEmail.toLowerCase()

This was selected as the best answer
sfdcfoxsfdcfox

SObject.get and SObject.set is case-insensitive, and automatically applies the namespace of the managed package it is called from, if any. Other than that, Starz is indeed correct.

SalesForce DummySalesForce Dummy

Worked like a charm. Thanks a bunch!!!

SalesForce DummySalesForce Dummy

I'll keep that in mind. Thanks, sfdcfox.