3/08/2012

ICEfaces radio buttons done right

When you are using ICEfaces then you have powerful features to display radio buttons on your page. 


ICEfaces allows you to separate the definition of the radio buttons from their placement, which makes it ideal to place them in complex UIs such as data tables, popups etc. This little tutorial will show you how to define radio buttons, how to place them and how to react to user interactions.


What you need to do first is to define your "selectOneRadio" elements. Those elements define the radio buttons that you can place anywhere on your page later. You have the possibility to define them statically in your xhtml or you can let a backing bean create  as many radio buttons as you want to have.


Here is a simple example of the finition part of two radio buttons:

<ice:selectOneRadio id="def" layout="spread" >

 <f:selectItem itemLabel="FirstChoice" itemValue="1"></f:selectItem>
 <f:selectItem itemLabel="SecondChoice" itemValue="2"></f:selectItem>


</ice:selectOneRadio>
This creates two radio buttons, labelled as "FirstChoice" and "SecondChoice" and "tells" ICEfaces, that those buttons may appear anywhere on the page by setting the layout type to "spread". But beware: This definition doesn´t display the radio buttons. To display them, you need to add the following :

<ice:radio for="def"   index="1"/>

<ice:radio for="def"   index="2"/>

Those tags actually display the radio buttons and you can put them wherever you like in the page. It also works great with dataTables.


This was the static part : displaying two predefined radio buttons.
But what if you want to display 1..n radio buttons ? Use the following to define your radio buttons:

<ice:selectOneRadio id="def" layout="spread" >

 <f:selectItems value="#{yourBean.radioButtonList}"></f:selectItem>
 
</ice:selectOneRadio>
And let it point to a simple List of SelectItems:
private List<SelectItem> firstList = new ArrayList<SelectItem>();
You can predefine this list with values and labels just as you always do, but remember the values you assign: You can use them to preselect a radio button. What you need to do now is to iterate over this list and display all the radio buttons:

<ice:radio for="def" index="#{yourBean.counter}"/>


If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.