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

Access saved data for field name stored in a variable



I have made a trigger and inside that trigger, I need to access saved data value, for field name stored in a string variable.

e.g. Account myAccount =[0];

String fieldName = 'Fax';

myAccount.Fax works;

myAccount.fieldName gives error.





trigger dsAccountTrigger on Account (after insert) {
Account myAccount =[0];

String query = 'select FieldName__c,MatchType__c from FieldMatchTypeRules__c where ObjectName = \'account\'';
matches = Database.query(query);

for(integer i = 0; i < matches.size(); i++)
String matchType = matches[i].MatchType__c;
String myFieldScore = '';

myFieldScore = myAccount.Fax;//This works
//This does not work
myFieldScore = myAccount.matches[i].FieldName__c;
//How to access field value saved in variable?


Do I need to have a different approach.


Please guide





You have to use the get/put notation if you want to access a field based on another variable. 


Something like the following should do the trick:



myFieldScore  = (String) myAccount.matches[i].get(fieldname);




You can use the get and put methods on an object to set or retrieve values for fields using either the API name of the field expressed as a String, or the field's token. In the following example, the API name of the field AccountNumber is used:


myFieldScore  = matches[i].get('fieldname');


Refer the apex-guide to know more about the dynamic apex concepts.


Hope this helps.


Thanks bob and pradeep,


myFieldScore  = (String) myAccount.matches[i].get(fieldname);

I changed it to
myFieldScore = (String) myAccount.get(matches[i].fieldName);
and it worked.