PostValidate数据表列表值

时间:2014-12-04 21:40:48

标签: jsf jsf-2 primefaces

我有一个使用h:datatable显示的项目列表,如下所示:

<p:dataTable value="#{myBean.instructorsList}" var="ins">
    <p:column headerText="Name">
        <h:inputText value="#{ins.name}"/>                                   
    </p:column>
</p:dataTable>

我的规格是我不允许教师与另一个教师同名。因此,我需要在提交时访问所有整个instructorList。我试图使用postValidate f:event验证,但是由于JSF生命周期,它在postValidation阶段之后才更新模型值。

我的尝试

<f:event listener="#{myBean.myMethod}" type="postValidate" />

支持代码

private List<instructors> instructorsList;

public void myMethod(ComponentSystemEvent event) {

  // Attempting to use the instructorsList with new values. However, this 
  // is at the wrong stage
}

如何编写验证器以完成对重复教师姓名的检查?

1 个答案:

答案 0 :(得分:0)

在监听器中,使用getSubmittedValue上的HtmlInputText方法直接从组件中提取值。此外,postValidate在语义上迟到会在验证过程中调用问题。请改用preValidate方法。总而言之,你应该

    public void myMethod(ComponentSystemEvent event) {
         HtmlInputText txtBox = (HtmlInputText)event.getComponent();
         String theValue = txtBox.getSubmittedValue().toString(); //the value in the textbox

         //based on the outcome of your validation, you also want to do the following

         FacesContext.getCurrentInstance().setValidationFailed(); //flag the entire request as failing validation
         txtBox.setValid(false); //mark the component as failing validation

    }

编辑:这种方法在很大程度上取决于您的用户一次只提交一行。在一个请求中提交整个表/列的情况下,您会发现逐个评估每个输入字段对防止竞争条件没有太大作用;你应该考虑进行跨领域验证。

编辑2:我错了,在调用事件监听器时你不能有竞争条件。按顺序为每一行执行监听器。这使您可以安全地检查每一行(可能针对重复项Map),而不必担心竞争条件。