第一个输入组件的模型值在第二个组件的验证器中为空

Model value of first input component is null in validator of second component

我需要通过 <f:attribute>:

获取 <p: selectOneMenu /> 的值以便在验证器中使用
<p:selectOneMenu id="tDocument" value="#{usuarioController.persona.tipoDocumento}">
    <f:selectItem itemLabel="#{msg.selectOne}" itemValue=""/>
    <f:selectItems value="#{tipeListController.tipoIdentificacion}" var="_tDocument" itemValue="#{_tDocument}"/>
</p:selectOneMenu>

<p:inputText id="doc" value="#{usuarioController.persona.num_documento}" required="true" validator="ciRucValidator">
    <f:attribute id="idenType" name="identificationType" value="#{usuarioController.persona.tipoDocumento}" />
</p:inputText>

但是当我尝试如下所示在验证器中获取它时,我得到 null:

TipoIdentificacion identificationType = (TipoIdentificacion) component.getAttributes().get("identificationType");

这是怎么造成的,我该如何解决?

模型值在第 4 阶段“更新模型值”期间设置。但是,在第 3 阶段“流程验证器”期间,验证器 运行。因此,这是一个更早的阶段。很明显,其他组件的更新模型值此时不可用。

规范的方法是只传递组件,然后根据组件的顺序通过 UIInput#getValue()UIInput#getSubmittedValue() 直接从中提取值。

<p:selectOneMenu binding="#{tDocument}" ...>
    ...
</p:selectOneMenu>
<p:inputText ... validator="ciRucValidator">
    <f:attribute name="tDocument" value="#{tDocument}" />
</p:inputText>

请注意,我删除了 <f:attribute id>this doesn't exist, and also note that binding example is as-is; very importantingly without a bean property

您可以在验证器中获取它,如下所示:

UIInput tDocument = (UIInput) component.getAttributes().get("tDocument");
TipoIdentificacion identificationType = (TipoIdentificacion) tDocument.getValue();
// ...

这也让您有机会在必要时通过 setValid(false) 使其他组件无效。

另请参阅:

  • How to get the value of another component in a custom validator?