Archive

Archive for the ‘JSF’ Category

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

2 April 2013 Leave a comment

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

<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

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.

Advertisements
Categories: Java, JSF, RichFaces Tags: , ,