2014-10-20 106 views
0

下拉列表與轉換器相關聯。 ajax在下拉值更改時有效。 但是,如果從下拉列表中選擇「 - 選擇 - 」項目,則ajax不會調用偵聽器。我找不到任何好的解決方案。代碼如下。f:ajax在下拉菜單下不起作用返回null

<h:selectOneMenu value="#{cc.attrs.beanProperty}" converter="myConverter" > 
    <f:selectItem itemValue="#{null}" itemLabel="-- Select --" /> 
    <f:selectItems value="#{cc.attrs.list}" var="item" itemValue="#{item}" itemLabel="#{item.name}" /> 
    <f:ajax render=":form1" listener="#{myBean.listener}"/> 
</h:selectOneMenu> 

轉換器:

@FacesConverter(value = "myConverter") 
public class VendorConverter implements Converter { 

    @Inject ObjectDAO dao; 

    @Override 
    public Object getAsObject(FacesContext context, UIComponent component, String value) { 
     if(value == null || value.contains("Select")){ 
      return null;    
     } 
     return dao.find(Integer.valueOf(value)); 
    } 

    @Override 
    public String getAsString(FacesContext context, UIComponent component, Object value) { 
     if(value == null) { 
      return null; 
     }     
     return ((MyObject) value).getId().toString(); 
    }  
} 

任何人可以點解?

回答

0

我找到了上述問題的一個棘手的解決方案。我想爲你分享。我已經放置了一個h:commandButton並使用jquery單擊該事件。所以當用戶從下拉列表中選擇-- Select -- Item時,它會執行必要的功能。

<h:selectOneMenu value="#{cc.attrs.beanProperty}" converter="myConverter" onchange="selectedItem(this)" > 
    <f:selectItem itemValue="#{null}" itemLabel="-- Select --" /> 
    <f:selectItems value="#{cc.attrs.list}" var="item" itemValue="#{item}" itemLabel="#{item.name}" /> 
    <f:ajax render=":form1" listener="#{myBean.listener}"/> 
</h:selectOneMenu> 

<h:commandButton class="reset" action="#{mybean.reset}" style="display: none;">    
    <f:ajax render="#{cc.attrs.renderComponent}"/> 
</h:commandButton> 


<script> 
    function selectedItem(that) {     
     if($(that).val() === ""){ 
       $(".reset").click(); 
     } 
    } 
</script> 
1

由於f:ajax不是由itemValue="#{null}"noSelectionOption="true"觸發(這是更好反正比null使用),我建議以下,從用戶避免回到- 選擇 -值之後,他已經選擇了內容

(除非你真的希望用戶能夠回到- 選擇 -選項後,他已經挑選了一些其他選項)

1)更換

<f:selectItem itemValue="#{null}" itemLabel="-- Select --" /> 

<f:selectItem noSelectionOption="true" itemLabel="-- Select --" /> 

2)添加使用itemDisabled這樣

<f:selectItem itemDisabled="#{not empty cc.attrs.beanProperty}" 
    noSelectionOption="true" itemLabel="-- Select --" /> 

或代替itemDisabled="#{not empty cc.attrs.beanProperty}"只使用<h:selectOneMenu hideNoSelectionOption="true">取決於你的喜好。


另外,還要注意的是,爲了找出什麼問題與您的代碼,你可以嘗試使用放置<h:message<h:messages在你的頁面

+0

@BalusC,謝謝,從來沒有使用過的那一個,我想這取決於設計者在這一個決定(我不喜歡的是,在頁面元素由他們自己:)即使隱含消失的想法它可以解釋和合理) – Daniel 2014-10-20 09:27:57