本文介绍了发生验证错误时,Ajax重置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有重置按钮的表格.此按钮的目的是重置表单的值.没有验证错误时,此方法可以正常工作.

I have a form with a reset button. The purpose of this button is to reset the values of the form. This works fine when there are no validation errors.

出现验证错误时,它不起作用.

When there is validation error, it does not work.

<h:form id="form">  
  <h:inputText id="v1" value="#{bean.value1}"/>
  <h:inputText id="v2" value="#{bean.value2}" required="true"/>
  <h:commandLink value="submit" action="#{bean.submit}">
    <f:ajax render="v1 v2"/>
  </h:commandLink> 
  <h:commandButton value="reset" action="#{bean.dummy}">
    <f:ajax render="@form" resetValues="true"/>
  </h:commandButton>
</h:form>

当我尝试在单击提交"按钮之前重设值时,所有值都将重设.

When I try to reset the values before clicking submit button, all values are reset.

当我在 v1 字段中输入一些值,而在 v2 字段中没有值时,按保存时,我会收到预期的验证消息.

When I enter some value at field v1 and no value in field v2, I get validation message as expected when save is pressed.

现在,我尝试通过单击重置按钮来重置Values.它只是重置无效字段 v2 .有效字段 v1 不会重置.

Now, I try to resetValues by clicking the reset button. It just resets the invalid field v2. The valid field v1 is not reset.

我错过了什么吗?

推荐答案

resetValues的名称有点误导.它仅重置组件状态.它不会重置模型值.您仍然要为此承担责任.

The resetValues has a somewhat misleading name. It resets only the component state. It doesn't reset the model values. You're still responsible for that yourself.

<h:commandButton value="reset" action="#{bean.reset}">
    <f:ajax render="@form" resetValues="true"/>
</h:commandButton>
public void reset() {
    value1 = null;
    value2 = null;
}

另一种方法是将type="reset"放在按钮中,这会将表单重置为初始状态,就像将页面呈现给最终用户时一样.

An alternative is putting type="reset" in the button, which will reset the form to its initial state as it was when the page was presented to the enduser.

<h:commandButton value="reset" type="reset" />

更好的是刷新页面.

<h:button value="reset" />

另请参见:

09-23 10:37