Action as JavaScript Function

The action component actionFunction allows you to call an Apex method in the controller as a JavaScript function. This decouples the user interface representation of the action from the action itself. You’ve already experienced action components that require a user to click a link or button to trigger a controller action. With actionFunction, you can call an action from anywhere in your page, including custom JavaScript code.

To use the actionFunction component, minimally specify an action to invoke in the action attribute, a JavaScript function name in the name attribute, and enclose it in a form component. Optionally, you can define arguments on the function by nesting param components inside the actionFunction tag. You can also define a JavaScript function to be invoked when the action is complete by using the oncomplete attribute.

Listings 7.3 and 7.4 contain page and controller code demonstrating the use of actionFunction and partial page refresh. It multiplies a number by two using a controller method exposed as a JavaScript function. The resulting value is displayed on the page using a pageMessages component and also refreshed in the call to the JavaScript function. This causes a stateful interaction in which the number is multiplied in a series.

Listing 7.3 Visualforce Page Using actionFunction


<apex:page controller="MyPageController7_3">
  <apex:outputPanel id="result">
    <apex:pageMessages />
    <a onclick="timesTwoFunction('{!value}'), return false;">
      Run
    </a>
  </apex:outputPanel>
  <apex:form>
    <apex:actionFunction name="timesTwoFunction"
      action="{!timesTwo}" reRender="result">
      <apex:param name="arg1" value="" assignTo="{!value}" />
    </apex:actionFunction>
  </apex:form>
</apex:page>


Listing 7.4 Visualforce Controller Using actionFunction


public class MyPageController7_3 {
  public Integer value { get; set; }
  public MyPageController7_3() {
    value = 1;
  }
  public PageReference timesTwo() {
    value *= 2;
    addInfo('The result is: ' + value);
    return null;
  }
  private void addInfo(String msg) {
    ApexPages.addMessage(new ApexPages.Message(
      ApexPages.Severity.INFO, msg));
  }
}


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.11.89