TransWikia.com

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

Salesforce Asked on January 4, 2021

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>

One Answer

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>

Correct answer by David Reed on January 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP