[SalesForce] Parameterized Custom Label

Is there a way to parameterize a custom label? Example:

Label name: MyTestLabel

Label value: Thank you, {0}, for your feedback.

Then in Apex, do something like this:

String name = 'John';
String label = Label.MyTestLabel;
String value = String.valueOf(label, name);

The idea being that the value variable would now hold "Thank you, John, for your feedback.

Best Answer

You can do this using the String.format() method which can provide parameter substitution on your label. The second parameter to this method is a List type and contains your parameters to be substituted.

Label name: MyTestLabel
Label value: Thank you, {0}, for your feedback.


List<String> parameters = new List<String>();
parameters.add('John');

String label = Label.MyTestLabel;
String value = String.format(label, parameters);

You can do it in one line like this as well:

string.format(Label.MyTestLabel, new String[]{'John'});
string.format(Label.MyTestLabel, new List<String>{'John'});