0

I have the following Controller and Visualforce(VF) page where I need to conditionally display a different value based on what is passed into a method.

Question

How can I pass a parameter into a method inside an if statement within a VF page?

Goal

  • based on the value of Account.myfield__c, change the URL that is displayed in the VF page

Current Issue:

  • When saving the VF page with the following code below, we get the "Syntax Error" message that does not allow me to save my changes

MyController.cls

public class MyController {

  public Boolean seeMyField(Id recordId) {
    Account acnt = [select Id, myfield__c from account where Id =: recordId limit 1];
   if(acnt.myfield__c > 100) {
      return true;
   }
   else {
      return false;
   }
  }
}

MyVfPage.page

<apex:outputLink value="{!IF(seeMyField({!Contact.Account.Id}), '/mytrue_url', /myfalse_url)}"> My link</apex:outputLink>
1

You can't evaluate arbitrary Apex expressions in Visualforce. You need to expose this value as a property on your class via a getter, such as

public Boolean seeMyField {
    get {
       Account acnt = [select Id, myfield__c from account where Id =: recordId limit 1];
       return acnt.myfield__c > 100;
    };
    private set;
}

You'll have to make sure the appropriate record Id can be referenced in the getter. Better would be to store the Account outside the getter, especially if you need to reference its properties multiple times, so that you don't query more often than you expect.

Then, in Visualforce,


<apex:outputLink value="{!IF(seeMyField, '/mytrue_url', '/myfalse_url')}"> My link</apex:outputLink>
2
  • Typo: missing quotes around the false expression – cropredy Oct 15 '20 at 6:47
  • Thanks, @cropredy! – David Reed Oct 15 '20 at 14:56

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.