2

This question is similar to the question here but that solution doesn't work here.

Take this simple-to-the-max example:

<h:form>
  <h:inputText required="true" value="#{mrBean.someValue}" />
  <h:inputText required="true" value="#{mrBean.someValue2}" />

  <h:commandButton value="Submit">
    <f:ajax execute="@form" />
  </h:commandButton>
  <h:commandButton immediate="true" action="#{mrBean.clearAllValues}" value="Clear">
    <f:ajax render="@form" />
  </h:commandButton>

</h:form>

And the bean Code:

public void clearAllValues() {
    setSomeValue(null);
    setSomeValue2(null);
}

Take this scenario:

  • Enter 'X' value in first input
  • Submit it using the 'Submit' Button. (failed in validation)
  • Enter 'Y' into the same input.
  • Click the 'Clear' button.
  • Result: Inputs don't clear and value of first input returns to 'X'.

I would expect this scenario to clear the input values but it doesn't, instead, it restores 'X' which is the previously submitted value. It actually never really runs mrBean.getSomeValue() on the bean (Which would have returned null and clear the input field)

The problem is related to JSF not working well with required fields and immediate. I wonder if anyone managed to overcome this problem.

Thanks! Ben.

Community
  • 1
  • 1
Ben
  • 10,020
  • 21
  • 94
  • 157

2 Answers2

5

Your code example is oversimplified. The described problem symptoms will only occur when you have multiple required inputs. Add one more required input field to the example. Fill out only one of them. A validation error will occur for the empty one. Then enter something else in both and press clear. The valid input will indeed retain the previously submitted value.

This problem is described in detail in this question and this blog article. The solution boils down to collecting all to-be-cleared input components and calling EditableValueHolder#resetValue() on each of them. This can be done with a <f:actionListener> as shown in the blog article.

Another way in your particular case since you just want to clear out the entire form is to use a <h:button> which will basically just refresh the page. If your bean is request or view scoped then it will also be recreated with all properties set to default.

<h:form>
  <h:inputText required="true" value="#{mrBean.someValue}" />

  <h:commandButton value="Submit">
    <f:ajax execute="@form" />
  </h:commandButton>
  <h:button value="Clear" />
</h:form>
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

Are you sure clearAllValues is executed? Do you get any errors in the logs or console? Try adding execute

<f:ajax render="@form" execute="@this">
roel
  • 2,005
  • 3
  • 26
  • 41