假设此页面的代码:
<h:form prependId="false" id="form"> <h:selectManyCheckbox id="checkBoxList" value="#{backedBean.lstIdSelectedItems}" layout="pageDirection"> <f:selectItems value="#{backedBean.lstAvailableItems}" var="item" itemLabel="#{item.label}" itemValue="#{item.value}" /> <f:ajax listener="#{backedBean.itemClicked}" /> </h:selectManyCheckbox> </h:form>
会话托管bean的代码:
public class BackedBean implements Serializable { private List<SelectItem> lstAvailableItems; private List<Long> lstIdSelectedItems; public BackedBean() { lstAvailableItems = new ArrayList<SelectItem>(); lstIdSelectedItems = new ArrayList<Long>(); } @PostConstruct private void postConstruct(){ for (int i = 0; i < 10; i++) { SelectItem item = new SelectItem(new Long(i), "CHKID " + i); lstAvailableItems.add(item); } } public void itemClicked(AjaxBehaviorEvent ae){ HtmlSelectManyCheckbox uiCmp = (HtmlSelectManyCheckbox)ae.getSource(); // (1) Here I would like to get the ID of the item that has been clicked. }
在(1)中,我想获取用户单击的元素的ID。我可以在lstIdSelectedItems数组列表中看到用户选择的所有元素的ID,但是如何获取用户单击的元素的ID?
我试图在selectManyCheckbox内使用f:attribute标记,但是当在支持的bean中调用ajax侦听器方法时,该属性不在组件映射中。我已经用过了,但是不起作用:
<h:selectManyCheckbox id="checkBoxList" value="#{backedBean.lstIdSelectedItems}" layout="pageDirection"> <f:selectItems value="#{backedBean.lstAvailableItems}" var="item" itemLabel="#{item.label}" itemValue="#{item.value}"> <f:attribute name="clicked" value="#{item.value}" /> </f:selectItems> <f:ajax listener="#{backedBean.itemClicked}" /> </h:selectManyCheckbox>
有任何想法吗?
问候。
因此,您不仅对新值感兴趣,而且对实际值更改感兴趣。引入一个valueChangeListener将旧值与新值进行比较的a ,并准备一些ajax侦听器方法可以拦截的属性。
valueChangeListener
例如
<h:selectManyCheckbox value="#{bean.selectedItems}" valueChangeListener="#{bean.selectedItemsChanged}" converter="javax.faces.Long"> <f:selectItems value="#{bean.availableItems}" /> <f:ajax listener="#{bean.itemSelected}" /> </h:selectManyCheckbox>
与
private Map<String, Long> availableItems; // +getter private List<Long> selectedItems; // +getter+setter private Long selectedItem; private boolean selectedItemRemoved; @PostConstruct public void init() { availableItems = new LinkedHashMap<String, Long>(); for (long i = 0; i < 10; i++) { availableItems.put("CHKID " + i, i); } } public void selectedItemsChanged(ValueChangeEvent event) { List<Long> oldValue = (List<Long>) event.getOldValue(); List<Long> newValue = (List<Long>) event.getNewValue(); if (oldValue == null) { oldValue = Collections.emptyList(); } if (oldValue.size() > newValue.size()) { oldValue = new ArrayList<Long>(oldValue); oldValue.removeAll(newValue); selectedItem = oldValue.iterator().next(); selectedItemRemoved = true; } else { newValue = new ArrayList<Long>(newValue); newValue.removeAll(oldValue); selectedItem = newValue.iterator().next(); selectedItemRemoved = false; } } public void itemSelected(AjaxBehaviorEvent event) { System.out.println("Selected item: " + selectedItem); System.out.println("Selected item removed? " + selectedItemRemoved); }