How to call parametrized function from Visualforce?

I have a parametrized helper function in my controller, which formats text according to requirements.

public static string getFormatMe(string a) {
    // do manipulation here
    return a;
}

How do I call this from Visualforce, to format my data?

This does not work:

<apex:outputText value="{!formatMe('test')}" />

Save error: Unknown function formatMe. Check spelling.

Here is a solution to a similar question, but that is for calling a function without parameters: How can I call a method from visualforce?

Answer

You cannot pass parameters to method bindings made in your Visualforce page to your controller, as per the help topic here, you can only provide ‘action’, ‘get’ and ‘set’ methods.

In order to implement your requirement I would recommend you consider looking at Visualforce Components, such that you can have something like

 <c:myOutputText myValue="test"/>
 <c:myOutputText myValue="{!MyObject__c.MyFieldToFormat__c}"/>

This component would internally use the apex:outputText component as above, however its controller would have been passed the ‘test’ value as an attribute to the component. On the controller you would have a getFormattedValue to output the formatted version.

<apex:component controller="MyOutputTextController">
  <apex:attribute name="myValue" type="String" description="Value to format" assignTo="{!myValueAttr}"/>
  <apex:outputText value="{!formattedValue}"/>
</apex:component>

Attribution
Source : Link , Question Author : Shumon Saha , Answer Author : Andrew Fawcett

Leave a Comment