Sunday, 13 August 2017

How to programmatically add a a4j:commandButton and a4j:actionparam ~ foundjava

After spending a few hours I finally managed to programmatically add an ajax command button and action parameter to JSF (1.2) components. So the following
1
2
3
4
5
6
<a4j:commandButton value="Click Me"
    styleClass="buttons" rendered="true" immediate="true"
    id="buttonId" actionListener="#{newRequestBean.doSomething}"
    ignoreDupResponses="true">
    <a4j:actionparam name="theVat" id="vatId" value="IComeFromTheBean" assignTo="#{newRequestBean.vat}" noEscape="false"/>
</a4j:commandButton>
translates to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
MethodExpression methodExpression = application.getExpressionFactory().createMethodExpression(
                                FacesContext.getCurrentInstance().getELContext(),
                                "#{newRequestBean.doSomething}",
                                null,
                                new Class[0]);
HtmlAjaxCommandButton button = (HtmlAjaxCommandButton) application.createComponent(HtmlAjaxCommandButton.COMPONENT_TYPE);
button.setValue("Click Me");
button.setStyleClass("buttons");
button.setRendered(true);
button.setImmediate(true);
button.setId("buttonId");
button.setIgnoreDupResponses(true);
button.setActionExpression(methodExpression);
 
ValueBinding vb = context.getApplication().createValueBinding("#{newRequestBean.vat}");
HtmlActionParameter param = (HtmlActionParameter) application.createComponent(HtmlActionParameter.COMPONENT_TYPE);
param.setId("vatId");
param.setName("theVat");
param.setValue("IComeFromTheBean");
param.setAssignToBinding(vb);
param.setNoEscape(false);
 
button.addActionListener(param);
button.getChildren().add(param);
Things to notice:
1) The last parameter of the method expression should be an empty array (new Class[0]), otherwise you will get the exception “java.lang.IllegalArgumentException: wrong number of arguments“. Your method should have no parameters.
2) You should add the HtmlActionParameter as the action listener of the command button. This is an absolutely essential step in order to make it work (well, this is only if you want to pass parameters to the call). It took me literally hours to figure this out.
3) The context variable is a FacesContext.

No comments:

Post a Comment