Felipe Cypriano

You're about to read

Grails With ZK: How to Create Components in Runtime With the Builder

ZKGrails plugin has an extremely nice feature which make easier than ever to create ZK components in runtime.

First lets see how is the usual way to create components in runtime using Java. This is the zul representation of what we’re trying to achieve:

1
2
3
4
5
<div>
  <toolbarbutton label="Clickable Item" href="#" />
  <toolbarbutton image="edit.png" if="${userHasAccess}" />
  <toolbarbutton image="delete.png" if="${userHasAccess}" />
</div>

And the java code to do the same:

1
2
3
4
5
6
7
8
9
10
11
12
Div div = new Div();
Toolbarbutton tbb = new Toolbarbutton("Clickable Item");
tbb.setHref("#");
tbb.setParent(div);
if (userHasAccess) {
    Toolbarbutton tbbEdit = new Toolbarbutton();
    tbbEdit.setImage("edit.png");
    tbbEdit.setParent(div);
    Toolbarbutton tbbDelete = new Toolbarbutton();
    tbbDelete.setImage("delete.png");
    tbbDelete.setParent(div);
}

As you can easily see the java code is pretty verbose. Using ZKBuilder the code will be easier to understand and smaller, take a look:

1
2
3
4
5
6
7
8
Div div = new Div();
div.append {
    toolbarbutton(label: "Clickable Item", href: "#")
    if (userHasAccess) {
        toolbarbutton(image: "edit.png")
        toolbarbutton(image: "delete.png")
    }
}

Which one do your prefer? :) If you want more continue reading to see how to use the builder as a template to a list of items.

Using ZKBuilder as a Template

I think the builder is specially useful when I’ve a list of items and I need to display these items with a specific layout one that the grid nor the listbox can provide. So I start as I started this post making the layout on a zul page and after I get what I want, I made a ZKBuilder version and put it in a loop to execute for each item I need to show.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ...
def items = myService.getItems()
items.each { item ->
    div.append {
        toolbarbutton(label: item.name, href:  item.link)
        if (userHasAccess) {
            toolbarbutton(image: "edit.png", onClick: {editItem item})
            toolbarbutton(image: "delete.png", onClick: {deleteItem item})
        }
    }
}
//...
public def editItem(def item) { /* code to edit the item */}
public def deletetem(def item) { /* code to delete the item */}

ZkBuilder is bundled in ZKGrails 0.7.6 and earlier. Enjoy!