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?

    How about storing your string in a variable and calling the getter function to work on that parameter?

    @ipavlic, thank you for your time and comment. I would not use variables because of the sheer number of the SOQL fields which need formatting.

    Perhaps a List which holds your fields?

  • 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>
    

    @SumanKrishnaSaha your very welcome! :)

    I don´t understand your response Andrew Fawcett. where do you specify to which function you use the attribute whose name is my value? and how do you get the returned string at the end? Thanks for your help.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used