Wednesday, June 6, 2012

Apache Wicket How to create a ListView with RadioGroup


Here is an example of showing a list of Employees under a department. We are using the RadioGroup and ListView Component for this example.

final Department department = (Department) this.getModelObject();
   ArrayList<Employee> employeesList = department.getEmployeesList();
//Create a Radio Group and then add a List View to this Radio Group As shown below.

RadioGroup<Integer> employeesRadioGroup = new RadioGroup<Integer>("employeesRadioGroup", new Model<Integer>(new Integer(0)));
employeesRadioGroup.add(new AjaxFormChoiceComponentUpdatingBehavior(){
/**
* 
*/
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
if(LOGGER.isDebugEnabled())
LOGGER.debug("Employee Radio Selected. You can add an Ajax Behavior on the selection of radio button.");
}
});
employeesRadioGroup.setOutputMarkupId(true);
employeesRadioGroup.setOutputMarkupPlaceholderTag(true);
employeesRadioGroup.setRenderBodyOnly(false);
add(employeesRadioGroup);

ListView empListView = new ListView("employeeListView", employeesList){
/**
*
* @see org.apache.wicket.markup.html.list.ListView#populateItem
*      (org.apache.wicket.markup.html.list.ListItem)
*/
@Override
protected void populateItem(final ListItem item) {

Employee employee = ((Employee)item.getModelObject());

String empId = employee.getEmployeeId();
String empName = employee.getEmployeeName();

if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Show Employee Record with Id :" + empId);
}
item.add(new Radio<Integer>("empSelectRadio", new Model<Integer>(item.getIndex()), employeesRadioGroup));
item.add(new Label("empId", empId).setEscapeModelStrings(false));
item.add(new Label("empName", empName) .setEscapeModelStrings(false));
}
};

if(employeesList.size() == 0){
error("No Employees Records Found.");
}

empListView.setOutputMarkupId(true);
empListView.setOutputMarkupPlaceholderTag(true);

employeesRadioGroup.add(empListView);


Here is the corresponding HTML to be added to your wicket Panel.

<table style="" wicket:id="employeesRadioGroup">
    <tr wicket:id="empListView">
        <td>
              <input type="radio" wicket:id="empSelectRadio"> <label wicket:id="empId">[Employee Id]</label>                                
        </td>
        <td>
            <a href="" wicket:id="empName">[Employee Name]</a>                                
        </td>
     </tr>
</table>

2 comments:

  1. From where did we get "hospitalAffiliationGroup" and how is it relevant here ?

    ReplyDelete
  2. Sorry its supposed to be employeesRadioGroup which is declared above. I have corrected the code. Thanks for pointing it out.

    ReplyDelete