Sunday, March 2, 2014

How to pass parameters with <a4j:jsFunction />

<a4j:jsFunction /> allowed us to send JSF ajax request with javascript function.

sample
<a4j:commandButton
    value="TEST"
    action="#{myBean.action}"
    oncomplete="myJsFunction();" />


<a4j:jsFunction name="myJsFunction" action="#{myBean.jsAction}" />


But the above implementation has a limitation,
where not allowed us pass parameter(s) to #{myBean.jsAction}

This issue could be resolved by adding <a4j:param /> under <a4j:jsFunction />
The <a4j:param /> associates to a property in managed bean, and inject the param value into managed bean before the action being fired.
Thus, the action (#{myBean.jsAction}) can get the param1 value from the getter.

sample
<a4j:commandButton
    value="TEST"
    action="#{myBean.action}"
    oncomplete="myJsFunction('myParam');" />


<a4j:jsFunction name="myJsFunction" action="#{myBean.jsAction}">
    <a4j:param name="param1" assignTo="#{myBean.param1}" />
</a4j:jsFunction>


@ManagedBean(name="myBean")
public class MyBean {

    private String param1;
    // getter, setter for param1
    public void jsAction {
        String newParam = getParam1() + "extra value";
        ......
    }
}



Done!!

4 comments:

  1. Thanks! Helped me with migrating Richfaces 3 to 4.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  3. there is no limitations, in RF you can also direct pass parameters, without additional setters.
    In bean use method with parameter:
    public void jsAction(String newParam) {
    ......
    }
    in form call this method and assign value by name for this parameter:
    < a4j:jsFunction name="myJsFunction" action="#{myBean.jsAction(newParam)}" >
    < a4j:param name="param1" assignTo="#{newParam}" / >
    < /a4j:jsFunction >

    ReplyDelete

LinkWithin

Related Posts Plugin for WordPress, Blogger...