[SalesForce] How to handle errors when using dynamic Custom Labels referencing

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?

Best Answer

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'.

Related Topic