【问题标题】:Exclude a form field from being submitted to backing bean using JavaScript/Ajax使用 JavaScript/Ajax 排除表单字段提交到支持 bean
【发布时间】:2018-08-06 23:36:08
【问题描述】:

如何排除 JSF 表单字段被提交给支持 bean? 我有很多字段,根据其中一个输入字段的条件,我想排除另一个字段的提交。

我将检查 JavaScript 中的条件,然后希望排除这个特定字段,使其不被提交到支持 bean。

【问题讨论】:

  • 我的一个简单猜测:你能从dom中删除输入元素吗?这应该导致它不被提交。但我不知道这是否有效。
  • 永远不要相信客户端(任何人都可以再次启用它)。只需添加一个条件服务器端,以确保它是例如未在业务逻辑中存储或使用。
  • 不是完全重复的.. 但相关:stackoverflow.com/questions/25339056/…

标签: javascript jsf jsf-2.2


【解决方案1】:

我能找到的最接近的副本是:Exclude field from a form in JSF。但是,它没有说明如何使用 JavaScript 来做到这一点。

正如 Kukeltje 已经指出的那样,我不会选择客户端解决方案。使用 Ajax 可以获得相同的结果。作为示例,我创建了一个表单,其中在选中复选框时提交值 1。如果未选中复选框,则将提交值 2。

<h:form>
  <h:panelGrid columns="3">
    <h:outputLabel for="check" value="Check"/>
    <h:selectBooleanCheckbox id="check" value="#{myBean.checked}">
      <f:ajax event="change" render="submit"/>
    </h:selectBooleanCheckbox>
    <h:message for="check"/>

    <h:outputLabel for="value1" value="Value 1"/>
    <h:inputText id="value1" value="#{myBean.value1}" required="true"/>
    <h:message for="value1"/>

    <h:outputLabel for="value2" value="Value 2"/>
    <h:inputText id="value2" value="#{myBean.value2}" required="true"/>
    <h:message for="value2"/>

    <h:commandButton id="submit" value="Submit">
      <f:ajax execute="#{myBean.execute()}" render="@form"/>
    </h:commandButton>
  </h:panelGrid>
</h:form>

提交规则的字段由命令按钮的&lt;f:ajax execute="..." 属性控制。它应该包含一个或多个客户端 ID,以空格分隔。在本例中,值是在支持 bean 中创建的:

public String execute() {
  return checked ? "value1" : "value2";
}

如您所见,它基于绑定到复选框的checked。如果选中value1,则应该执行,否则value2

为了更新命令按钮的execute 属性,我在复选框中添加了&lt;f:ajax event="change" render="submit"/&gt; 以更新命令按钮(及其执行客户端ID)。

我已在字段中添加了必填项,以表明如果您将其中一个字段都留空,则会显示错误消息。

您可以使用输入字段的渲染属性获得相同的效果:

<h:form>
  <h:panelGrid columns="3">
    <h:outputLabel for="check" value="Check"/>
    <h:selectBooleanCheckbox id="check" value="#{myBean.checked}">
      <f:ajax event="change" render="@form"/>
    </h:selectBooleanCheckbox>
    <h:message for="check"/>

    <h:outputLabel for="value1" value="Value 1"/>
    <h:inputText id="value1" value="#{myBean.value1}" required="true"
                 disabled="#{not myBean.checked}"/>
    <h:message for="value1"/>

    <h:outputLabel for="value2" value="Value 2"/>
    <h:inputText id="value2" value="#{myBean.value2}" required="true"
                 disabled="#{myBean.checked}"/>
    <h:message for="value2"/>

    <h:commandButton id="submit" value="Submit">
      <f:ajax execute="@form" render="@form"/>
    </h:commandButton>
  </h:panelGrid>
</h:form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2021-09-30
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多