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
steve_andersensteve_andersen 

Using Variables for field names in update statement

I have an S-Control that I'm rewriting in Apex. The S-Control looks at opp data and then dynamically decides on which Contact fields to update. The set statement looks like this:
Contact.set(oFields[fy], oTotals[cid][DonationRecordType+fy]);
I'd like to do the same thing in Apex. I've got a Map of fieldname and value:
Map<String,Double> Yearlytotals = new Map<String,Double>();
and I'm filling it successfully:
Yearlytotals.put(CloseYear,ThisYearAmount);
How should I contruct my Update statement? I'd like to loop through my set and get the field name and the value like this:
for(String CurrentYear:Yearlytotals.keySet()) {
    //this is the field name
    system.debug(CurrentYear);
    //this is the value
    system.debug(Yearlytotals.get(CurrentYear));
}
I'd like to then set the fields on my Contact object to equal the values. Every update example I can find identifies the fields with the explicit name:
Contact UpdateContact = new Contact (
    Id=GiverId,
    FY2005__c=ThisYearAmount   
);
update UpdateContact;

Can I identify fields with a String variable like I could in an S-Control Set statement? Can you point me to an example where Apex "Set" statements are generated from interating through a set?

Thanks,
Steve
steve_andersensteve_andersen
I figured the easy part of the question--looping through the map and getting the values for assignement to fields on the Contact.

I haven't figured out how to do the "set" statements like I did in my S-Controls, so any help on that one is appreciated!

Thanks,

Steve
steve_andersensteve_andersen
Got an offline answer from an sf.com staffer that you cannot do what I'm trying to do.

Steve
TheDevLifeTheDevLife

Steve,

You already may know this but just wanted to be clear. As you mentioned, there is no way right now in Apex code to use a variable to represent the field name. However, you still can access the fields using the Dot notation. So in your example, you can say

 

Contact C=new Contact();

c.Id=GiverId;

c.FY2005__c=ThisYearAmount;

etc.

 

You then build an array of these and use an Update command to update them. This still is fairly flexible. Having the field names in variables becomes more important if your trying to build a generic type class or process.

 

Randy

 

steve_andersensteve_andersen
Thanks, Randy. That's what I understood after getting some more info.

We've got s-control code that looks at Opp close dates and decides which rollup fields to update on the Contact. So, for now, we'll have to list all our fields in our Apex code, and only use the ones that need to be updated. Less elegant than the s-control code, but it will work.

Thanks,
Steve