【问题标题】:Mutually exclusive input fields with JSF and PrimeFaces具有 JSF 和 PrimeFaces 的互斥输入字段
【发布时间】:2016-10-03 18:45:39
【问题描述】:

我有一个 PrimeFaces 应用程序,我想让两个输入文本字段互斥:用户应该填写其中一个字段,但不能同时填写。

在以下示例中,用户可以通过电话号码或电子邮件搜索联系人。

<h:form>
    <h:outputLabel>Phone Number:
        <h:inputText id="phoneInput" value="#{contactSearch.phone}"
                     disabled="#{not empty contactSearch.email}">
            <p:ajax event="keyup" update="emailInput"/>
        </h:inputText>
    </h:outputLabel>
    <h:outputLabel>Email Address:
        <h:inputText id="emailInput" value="#{contactSearch.email}"
                     disabled="#{not empty contactSearch.phone}">
            <p:ajax event="keyup" update="phoneInput"/>
        </h:inputText>
    </h:outputLabel>

    <!-- Possibly other fields... -->

    <h:commandButton value="Search" action="#{contactSearch.search}"/>
</h:form>

这是正确的方法吗?我担心:

  • 可能的“死锁”问题,两个字段最终都被禁用
  • 当我只想更新输入字段的 disabled 状态时,在 Ajax 请求中提交和/或验证的整个表单
  • 缺少一些完成所有工作的预定义 PrimeFaces 控件:)

【问题讨论】:

    标签: validation jsf jsf-2 primefaces


    【解决方案1】:

    这在标准的 JSF 中不是微不足道的。 JSF 实用程序库OmniFaces 有一个用于此目的的验证器&lt;o:validateOne&gt;

    <h:inputText id="email" ... />
    <h:inputText id="phone" ... />
    <o:validateOne components="email phone" />
    

    但是,从UX 的角度来看,您最好重新设计表单以提供单个UISelectOne 组件来选择类型和单个UIInput 字段来输入值。例如

    <h:selectOneRadio ... value="#{bean.type}">
        <f:selectItem itemValue="email" />
        <f:selectItem itemValue="phone" />
    </h:selectOneRadio>
    <h:inputText ... value="#{bean.value}" />
    

    更新:由于服务器端验证负担不起,并且您真的想禁用另一个而不产生太多 ajax 流量,您唯一的选择是使用纯 JavaScript/jQuery 来完成这项工作(如果需要结合服务器端验证作为后备)。

    这是一个基于 jQuery 的通用方法:

    <h:inputText styleClass="onlyone" a:data-onlyone="groupName" />
    <h:inputText styleClass="onlyone" a:data-onlyone="groupName" />
    ...
    

    $(document).on("input", ":input.onlyone", function() {
        var $this = $(this);
        var $others = $("[data-onlyone='" + $this.data("onlyone") + "']").not($this);
        $others.val(null).attr("disabled", !!$this.val());
    });
    

    data-onlyone 值应该代表组名,因此您可以在整个文档中拥有多个“只有一个”输入。

    【讨论】:

    • 实际示例来自“高级搜索”页面,用户无需填写任一字段。 &lt;o:validateOne&gt; 和相关的&lt;o:validateOneOrNone&gt; 只能事后警告用户……但不能防止错误。
    猜你喜欢
    • 2013-08-14
    • 2018-04-21
    • 2014-02-24
    • 2023-03-12
    • 2018-11-08
    • 2022-11-28
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    相关资源
    最近更新 更多