Getting selected items in listbox ZK

Reading Time: < 1 minute

In one of my project I really needed one of piece of this code and dwelled on that for a long while. I asked for assistance from a senior and he showed me how to, and I would like to share this piece of helpful code with you. In controller class I did not create a simple arraylist for the listbox model just to give you the structure you may implement this code in your project. Normally for one lastly selected item you can use listbox.getSelectedItem.getValue() and acquire the selected item. How about when we have more than one selected items, that is the tricky point

The trick I learnt was that there was an iterator in the listbox, and I saw that I could easily collect the selected items. You will see how I achieved that thanks to the Senior.

Controller

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class BulkAuthController extends SelectorComposer<Component> {

@Wire
Listbox universeListbox;

//I have this simple array list to collect the selected items on listbox not mandatory
private ArrayList<String> selectedUniverseListboxItems = new ArrayList<String>();

//here is the trick.
public void collectSelectedItems() {
		Iterator<Listitem> iterator = universeListbox.getSelectedItems()
				.iterator();
		while (iterator.hasNext()) {
			Listitem listitem = (Listitem) iterator.next();
			selectedUniverseListboxItems.add(listitem.getValue().toString());
		}
	}

}

Zul Page

<?page title="Listbox Test" contentType="text/html;charset=UTF-8"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit"?>
<zk xmlns:h="http://www.w3.org/1999/xhtml"
	xmlns:zk="http://www.zkoss.org/2005/zk">

	<window id="listboxSample" title="Listbox Test" border="normal"
		width="900px" apply="com.tugrulaslan.controller.ListboxTestController">

					<listbox id="universeListbox"
						model="${$composer.userUniverseList()}" multiple="true"
						checkmark="true" height="500px">
						<template name="model">
							<listitem>
								<listcell label="${each}"
									value="${each}">
								</listcell>
							</listitem>
						</template>
					</listbox>
	</window>
</zk>