2014-10-20 101 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