13

Any ideas how to prevent error when trying dynamically access label which doesn't exist? Check somehow whether it exists before referencing or maybe catch this error.

Here is my page:

<apex:page Controller="MyController">
    <apex:outputText> {!$Label[label.labelName]} </apex:outputText>
</apex:page>  

And here is errror:

Field $Label.myLabel does not exist. Check spelling
Error is in expression '{!$Label[label.labelName]}' in component <apex:repeat> in page pagename
Error evaluating dynamic reference 'myLabel'

Related topic: possible to access custom labels dynamically?

  • Why use a dynamic reference in the first place? – Adrian Larson Oct 23 '14 at 23:08
  • If the name of the label is something you solicit from the user, how about validating that at the time it is captured? Then if the label is deleted later, it's on their own head. – bigassforce Jan 4 '15 at 12:47
  • I tried Varun's APEX workaround in the question that was referenced by you. Unfortunately that doesn't work either, because when you input an invalid label via APEX, it throws an "Internal Salesforce Error" which cannot be caught. – Guy Clairbois Sep 30 '16 at 12:05
0

Well, since you are already using labels as fields in the controller, why not simple render their value with a standard binding?

E.g. controller:

public class MyController
{
    public String mylabel1 {get; set;}
    public String mylabel2 {get; set;}

    public MyController()
    {
         mylabel1='label one';   
         mylabel2='label two';   
    }
}


VF page:

<apex:page Controller="MyController">
    <span> {!mylabel1} </span>
    <span> {!mylabel2} </span>
</apex:page>


Should you by any chance try to add a binding referencing a field which does not exist in the controller (e.g. mylabel3), you won't be able to save your changes as you will get Save error 'Unknown property'.

  • 4
    This won't support all the features of labels, like overrides for managed packages, or language-specific translations that are automatically used based on use locale. – ca_peterson Mar 17 '14 at 18:03
  • You can reference Labels in Apex as well. String foo = Label.myLabel; – ScottW Sep 16 '14 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.