10 September 2009

Show/hide controls dynamically in JSF

We often need to show a set of controls dynamically based on what a user selects in a component in JSF. This example shows how to accomplish this in JSF and Seam, using the JBoss' EL extensions, which make life easier in your XHTML tags.

In this case, we're using an h:selectOneRadio control. We want to show and hide the rich:Panel controls; we wrap them in an a4j:outputPanel and then just re-render that when the user clicks a radio element. Note that for radio buttons, we have to use the onclick event; onchange is for h:selectOneMenu and other select controls.
<h:selectoneradio value="#{webencode.requestType}" id="rdoRequestType" styleclass="radio" layout="pageDirection">
<f:selectitem itemvalue="program" itemlabel="Series or Program">
<f:selectitem itemvalue="special" itemlabel="Special">
<a4j:support ajaxsingle="true" event="onclick" rerender="program">
</a4j:support>

<a4j:outputpanel id="program">
<rich:panel rendered="#{webencode.checkRequestType('program')}">
program stuff goes here
</rich:panel>
<rich:panel rendered="#{webencode.checkRequestType('special')}">
special stuff goes here
</rich:panel>
</a4j:outputpanel>
We can't call the equalsIgnoreCase() method on a string from within an EL expression, so we use a Seam method call that returns true/false based on string equality:
public Boolean checkRequestType(String requestType){
return (this.requestType.equalsIgnoreCase(requestType)) ? true : false;
}
With the a4j:support tag, we use AJAX to re-render the a4j:outputPanel when the user clicks the radio buttons. Then the custom checkRequestType() bean method is called and returns a Boolean based on the value of the radio button group.

2 comments:

Anonymous said...

quite difficult for fresher to understand this code

random said...

thanks dev