Wicket – Updating ListViews using an AjaxLink

04 Jun, 2008
Xebia Background Header Wave

Consider the following senario: we want to display some data in a table like manner, and we want it to update when we click on a link or button. We do not want to do a complete page refresh, we want it in an ajax way. Also we would like the modify the css for each cell.
In wicket you can use a ListView iterate over a List of Objects and display them in a table like manner.
This blog describes how you can update ListView data and modify the css for each cell.

So how do we start?
Well first we need to create a ListView. Lets call it view.
But before we do that we need a List of objects we want to display. So lets create it.
I use a List of TestObject’s.
As you can see below, this isn’t very hard.

private ListView view;
private List objects;
objects = Arrays.asList(new TestObject[] {
    new TestObject("one", true),
    new TestObject("two", false),
    new TestObject("three", true)});
view = new ListView("view", objects) {
    protected void populateItem(ListItem item) {
        Label label = new Label("label", new PropertyModel(item.getModel(), "name"));

Next we will create an IndicatingAjaxFallbackLink which is basically a AjaxLink that shows an indicator.

private IndicatingAjaxFallbackLink link;
link = new IndicatingAjaxFallbackLink("link") {
    public void onClick(AjaxRequestTarget target) {
        objects = Arrays.asList(new TestObject[] {
            new TestObject("four", false),
            new TestObject("five", true),
            new TestObject("six", false)});
        target.addChildren(view, Label.class);

Thats all. Now see that we add a new List of objects to the ListView. To make sure the ListView is updated we add

target.addChildren(view, Label.class);

instead of


. As a ListView is a repeater, we cannot updated it, but we can update components in a ListView.
So now we can update a ListView, but how do we change the css for each field?
We add an AttributeModifier. In the populateItem method show above we just add the following

label.add(new AttributeModifier("class", true, new PropertyModel(item.getModel(), "odd") {
    public Object getObject() {
        return ((Boolean) super.getObject()) ? "odd" : "even";

The getObject method is overridden, because the method getOdd() on the TestObject returns a boolean. So instead of returning true or false, it now returns "odd" or "even" which are css class styles.
That’s it.
I have attached the example project here so you can look into the code yourself.


Get in touch with us to learn more about the subject and related solutions

Explore related posts