01: /* SelectedItemConverter.java
02:
03: {{IS_NOTE
04: Purpose:
05:
06: Description:
07:
08: History:
09: Tue Dec 12 15:43:28 2006, Created by Henri
10: }}IS_NOTE
11:
12: Copyright (C) 2006 Potix Corporation. All Rights Reserved.
13:
14: {{IS_RIGHT
15: }}IS_RIGHT
16: */
17: package org.zkoss.zkplus.databind;
18:
19: import org.zkoss.zul.Listbox;
20: import org.zkoss.zul.Listitem;
21: import org.zkoss.zul.ListModel;
22:
23: import org.zkoss.zk.ui.Component;
24: import org.zkoss.zk.ui.UiException;
25: import org.zkoss.zk.ui.event.Event;
26: import org.zkoss.zk.ui.event.Events;
27: import org.zkoss.zk.ui.event.SelectEvent;
28:
29: import java.util.Set;
30: import java.util.HashSet;
31: import java.util.Iterator;
32:
33: /**
34: * Convert selected item to bean and vice versa.
35: *
36: * @author Henri
37: */
38: public class SelectedItemConverter implements TypeConverter {
39: public Object coerceToUi(Object val, Component comp) { //load
40: Listbox lbx = (Listbox) comp;
41: if (val != null) {
42: final ListModel xmodel = lbx.getModel();
43: if (xmodel instanceof BindingListModel) {
44: final BindingListModel model = (BindingListModel) xmodel;
45: int index = model.indexOf(val);
46: if (index >= 0) {
47: final Listitem item = (Listitem) lbx
48: .getItemAtIndex(index);
49:
50: final int selIndex = lbx.getSelectedIndex();
51:
52: //We need this to support load-when:onSelect when first load
53: //the page in (so it is called only once).
54: if (item != null && selIndex != index) { // bug 1647817, avoid endless-loop
55: Set items = new HashSet();
56: items.add(item);
57: Events.postEvent(new SelectEvent("onSelect",
58: lbx, items, item));
59: }
60: return item;
61: }
62: } else if (xmodel == null) { //no model case, assume Listitem.value to be used with selectedItem
63: //iterate to find the selected item assume the value (select mold)
64: for (final Iterator it = lbx.getItems().iterator(); it
65: .hasNext();) {
66: final Listitem li = (Listitem) it.next();
67: if (val.equals(li.getValue())) {
68: return li;
69: }
70: }
71: } else {
72: throw new UiException(
73: "model of the databind listbox "
74: + lbx
75: + " must be an instanceof of org.zkoss.zkplus.databind.BindingListModel."
76: + xmodel);
77: }
78: }
79: return null;
80: }
81:
82: public Object coerceToBean(Object val, Component comp) { //save
83: Listbox lbx = (Listbox) comp;
84: if (val != null) {
85: ListModel model = lbx.getModel();
86: //no model case, assume Listitem.value to be used with selectedItem
87: return model != null ? model.getElementAt(((Listitem) val)
88: .getIndex()) : ((Listitem) val).getValue();
89: }
90: return null;
91: }
92: }
|