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