Dynamically Retrieve And Update Field as Variables

Sometimes you would like to update fields by using their field names as variables. I have found the dynamic fetching and updating of SObject fields very efficient.

I have an method that needs to update a specific User field with 4 different values. Without parsing 4 parameters and doing allot of if statement I can now get the field by it’s name and update it in one line.

SObject s = [SELECT Name FROM Account LIMIT 1];
Object o = s.get('Name');
s.put('Name', 'abc');
update s;

Now you can use it in a method

public static User updateUserRecordCount(User userToUpdateCount, String dateTimeField)
   userToUpdateCount.put(dateTimeField, DateTime.Now());
   return userToUpdateCount;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s