在同一组件中使用JSF绑定+验证器显示消息两次

时间:2012-07-26 19:51:04

标签: jsf

我有2个组件(select和inputText),其中值相互依赖。例如,如果选择“选项1”,则inputText必须是数字。

在我的bean中,我为绑定和验证方法添加了2个组件的属性,而在jsp中,我添加了“validator”和“binding”属性来选择和“绑定”到inputText。

我使用绑定来获取两个组件的提交值以进行验证。

这是正确的方法吗?是否有替代方法可以获得提交的值?

执行此操作的结果是显示重复消息。如果我从select中删除绑定属性,那么它按预期工作但我无法获取所选值,而是使用缓存值(会话中的bean值)。

提前致谢。

aalmero

代码:

<p:selectOneMenu
value="#  {deploymentRequestViewBean.deploymentRequestDTO.deploymentRequest.requestLevel}"
id="requestLevel" required="true" label="requestLevel" 
validator="#{deploymentRequestViewBean.validateRequestDate}">
<p:ajax listener="#{deploymentRequestViewBean.processRequestLevelValueChanged}" 
binding="#{deploymentRequestViewBean.requestLevelSelectOne}"/>
<f:selectItem itemValue="" itemLabel="Select One" />
<f:selectItem itemValue="DEV" itemLabel="DEV" />
<f:selectItem itemValue="QUA" itemLabel="QUA" />
<f:selectItem itemValue="PRD" itemLabel="PRD" />
</p:selectOneMenu>

 <p:calendar
 value="#{deploymentRequestViewBean.deploymentRequestDTO.deploymentRequest.deployDate}"
 id="deployDate" required="true" label="deployDate" showOn="button" pattern="yyyy-  MM-dd" binding="#{deploymentRequestViewBean.requestDateInput}"/>
<p:spacer width="10" height="10" /> 

//for component-binding
private UISelectOne requestLevelSelectOne;
private UIInput requestDateInput;


//validation method
public void validateRequestDate(FacesContext facesContext,
    UIComponent component, Object newValue){

//get the current value of select;
requestLevelSelectOne.getSubmittedValue();
//get the current vallue of input;
requestDateInput.getSubmittedValue()

if(not valid combination){
           facesContext.addMessage(requestDateInput.getClientId(facesContext), new  FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", selectedLevel + " deployment request requires at least 2 days."));
        throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Deployment date must be at least 2 days."));
}
}

1 个答案:

答案 0 :(得分:0)

您可以通过将隐藏的组件值与select组件绑定来使用hack bypass。在<h:selectOneMenu>的“onchange”方法中,您可以设置此隐藏组件的值并获取服务器中的值:

<h:form id="myForm">
    <h:selectOneMenu id="cmbOptions"
        onchange="document.getElementById('myForm:hidSelectOption').value=this.value">
        <f:selectItem itemLabel="Option 1" itemValue="1" />
        <f:selectItem itemLabel="Option 2" itemValue="2" />
        <f:selectItem itemLabel="Option 3" itemValue="3" />
    </h:selectOneMenu>
    <h:inputHidden id="hidSelectOption" value="#{bean.selectedOption}" />
    <h:commandButton value="Click me" action="#{bean.someAction}" />
</h:form>

托管Bean

@RequestScope
@ManagedBean
public class Bean {
    private String selectedOption;
    //getters and setters...
    public Bean() {
    }

    public void someAction() {
        //showing the actual value of the hidden component...
        //remember that you should use a logger, this is a basic example
        System.out.println(selectedOption);
    }
}