You need to sign in to do that
Don't have an account?
steve_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:
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
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
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
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
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