簡體   English   中英

JSF selectOneMenu驗證和Ajax渲染

[英]JSF selectOneMenu validation and ajax rendering

我在selectOneMenu上進行了驗證,以防止用戶在列表中選擇“無”項目。

<h:selectOneMenu id="selectMenu" value="#{bean.selectedValue}" required="true" requiredMessage="Please select an item">
    <f:ajax render="toRender selectMenuMessage" listener="#{bean.onSelect}"/>
    <f:selectItem itemLabel="None" noSelectionOption="true"/>
    <f:selectItems value="#{bean.items}" var="item" itemValue="#{item.id}" itemLabel="#{item.label}"/>
</h:selectOneMenu>

我的面板在下面,並且只想在我的項目不是“無”時才顯示它。 因此,當我選擇“無”時,消息應呈現,面板消失。

<h:panelGroup id="toRender">
    <h:panelGrid rendered="#{bean.selectedValue == 0 ? false : true">
        ...
    </h:panelGrid>
</h:panelGroup>

它沒有驗證就可以工作,但是我不能同時做這兩個工作。就像驗證阻止了渲染一樣。

有什么建議嗎? 謝謝

我猜bean.selectedValue是一個整數,所以試試這個:

<f:selectItem itemValue="0" itemLabel="None" noSelectionOption="true"/>


編輯:抱歉,我認為您的問題有點誤解了。
這里的問題是,如果您需要為selectOneMenu設置一個值,則該值為空時將不會提交。 並且,如果選擇了帶有noSelectionOption="true"的項目,則它將被視為空,因此不會提交任何值。 當您檢查bean.selectedValue == 0selectedValue將永遠不會為0(可能最初除外)為0,因為如上所述,當您選擇值為0的項目時,它將不會被提交。
因此,您是對的,您的驗證和bean.selectedValue == 0的檢查不能一起使用。 我建議您只刪除驗證。
如果這不是您的選擇,請向我解釋為什么您需要它以這種方式進行更多詳細說明。

我有一個回應,這不是解決方案,但這是實現此目標的另一種方式...

<h:selectOneMenu id="selectMenu" value="#{bean.selectedValue}">
    <f:ajax render="toRender selectMenuMessage" listener="#{bean.onSelect}"/>
    <f:selectItem itemLabel="None" noSelectionOption="true"/>
    <f:selectItems value="#{bean.items}" var="item" itemValue="#{item.id}" itemLabel="#{item.label}"/>
</h:selectOneMenu>

然后在豆子里

public void onSelect() {
    if(this.selectedValue != 0) {
        // Do smthg here
    } else {
        // Display error message
        UIComponent component = Outils.getFacesContext().getViewRoot().findComponent(":form:selectMenu");
        if(component != null) {   
            Outils.getFacesContext().addMessage(component.getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "Test msg"));
        }
    }       
}

這樣,不會啟動驗證過程,而是在Bean中完成驗證。

如果有人找到更好的東西,讓我知道!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM