Primefaces,自动完成,多种模式.如何避免两次选择相同的项目?

Ana*_*oly 6 jsf primefaces

我知道我不能直接在Primefaces中做到这一点,我知道我必须在转换器中做到这一点但不知道在哪个阶段以及如何?我应该检查什么?也许这样做我需要楔入JSF的生命周期?例如,在p:自动完成后,在" 应用请求值阶段 " 中将列表添加到列表中,如果我以正确的方式理解JSF生命周期,我应检查是否存在重复项并在" 更新模型值阶段 " 之前将其删除?有可能吗?先感谢您.

Xtr*_*ica 10

这是可能的,您需要做的是让每个用户选择/取消选择的模型保持最新.这是使用<p:ajax />标签进行的<p:autoComplete />,因此List所选项目将在后端更新.稍后,当用户请求其他查询时,请注意这一点List.

看看这个SSCCEListString值(你可以选择使用Converter或不适合你的自定义类,但不是在所有与你的问题相关的):

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:p="http://primefaces.org/ui">
<h:head />
<h:body>
    <h:form>
        <p:outputLabel value="Multiple:" />
        <p:autoComplete multiple="true"
            value="#{autoCompleteBean.selectedItems}"
            completeMethod="#{autoCompleteBean.completeItem}" var="it"
            itemLabel="#{it}" itemValue="#{it}" forceSelection="true">
            <p:ajax event="itemSelect" />
            <p:ajax event="itemUnselect" />
            <p:column>
                <h:outputText value="#{it}" />
            </p:column>
        </p:autoComplete>
    </h:form>
</h:body>
</html>
Run Code Online (Sandbox Code Playgroud)
@ManagedBean
@ViewScoped
public class AutoCompleteBean {

    /**
     * The items currently available for selection
     */
    private List<String> items = new ArrayList<String>();

    /**
     * Current selected items
     */
    private List<String> selectedItems = new ArrayList<String>();

    /**
     * All the items available in the application
     */
    private List<String> allItems = new ArrayList<String>();

    /**
     * Create a hardcoded set of items and add all of them for selection
     */
    public AutoCompleteBean() {
        allItems.add("item1");
        allItems.add("item2");
        allItems.add("item3");
        allItems.add("item4");
        items.addAll(allItems);
    }

    /**
     * Check the current user query for selection. If it fits any of the items
     * of the system and it's not already selected, add it to the filtered List
     * 
     * @param query
     * @return
     */
    public List<String> completeItem(String query) {
        List<String> filteredList = new ArrayList<String>();
        for (String item : allItems) {
            if (item.startsWith(query) && !selectedItems.contains(item)) {
                filteredList.add(item);
            }
        }
        return filteredList;
    }

    public List<String> getItems() {
        return items;
    }

    public List<String> getSelectedItems() {
        return selectedItems;
    }

    public void setSelectedItems(List<String> selectedItems) {
        this.selectedItems = selectedItems;
    }

}
Run Code Online (Sandbox Code Playgroud)