Ajax reset value when validation error happens

2019-06-14 05:56发布

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.

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

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

Am I missing any thing.

1条回答
冷血范
2楼-- · 2019-06-14 06:36

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;
}

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" />

Much better is just refreshing the page.

<h:button value="reset" />

See also:

查看更多
登录 后发表回答