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
GailGail 

Pass field name as a variable in getinstance

I have code that looks up a value in a custom field in a Custom Setting, kind of like below:

 

My_Custom_Setting__c.getInstance(a.Name).Custom_Field__c

 

Depending on some variable, "Custom_Field__c" could be one of 2 fields. I tried setting a string to the proper field name and then using that string in my get instance statement, kind of like below:

 

string custom_field;

if (something) {

string = 'Custom_Field_1__c';

}

else string = 'Custom_Field_2__c';

 

My_Custom_Setting__c.getInstance(a.Name).custom_field;

 

Of course, it looks for the field "custom_field" rather than replacing "custom_field" with "Custom_Field_1__c" or "Custom_Field_2__c". How do I get it to do what I want? 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
GailGail

I tried both of the above but didn't get the results I wanted. Then I realized that I really only had 3 different statements using 2 different field values so I set a string to the entire statement before running through the code. Worked like a charm. 

 

Basically, it looked like:

 

String SettingLookup;

If (factor X){
String SettingLookup = 'MyCustom_Setting__c.getinstance(a.name).Factor_X_Field__c';
}
else {
SettingLookup = 'MyCustom_Setting__c.getinstance(a.name).Factor_Y_Field__c';
}

 and then I just called SettingLookup later. 

All Answers

Avidev9Avidev9

I guess you have to use the get  method of Sobject.

 

Something like this

 

My_Custom_Setting__c.getInstance(a.Name).get(custom_field);

 To explain more let us assume you have a Sobject and you want to access the value of Name field, so the code will be

Account acc = [SELECT Name FROM Account LIMIT 1];
String name = acc.get('Name');

 

krprkrpr

Try this : 

 

My_Custom_Setting__c.getInstance('a.name ').Custom_Field__c;

 

replace a.name with a.name  value in single quotes

GailGail

I tried both of the above but didn't get the results I wanted. Then I realized that I really only had 3 different statements using 2 different field values so I set a string to the entire statement before running through the code. Worked like a charm. 

 

Basically, it looked like:

 

String SettingLookup;

If (factor X){
String SettingLookup = 'MyCustom_Setting__c.getinstance(a.name).Factor_X_Field__c';
}
else {
SettingLookup = 'MyCustom_Setting__c.getinstance(a.name).Factor_Y_Field__c';
}

 and then I just called SettingLookup later. 

This was selected as the best answer