lundi 20 février 2017

JSF reset conditionally rendered input field

Whenever I try to reset the value of a conditionally rendered field, it reverts to a previously entered value instead of a null value.

The following is an explanation of the unexpected behavior:

  1. checkbox is true --> textfield is rendered
  2. enter 'test' into textfield
  3. uncheck checkbox --> texfield is not rendered
  4. click reset button --> checkbox value = true && textfield value = null
  5. expected --> inputtextfield with null value
  6. actual --> inputtextfield with 'test' value

Simplified example

Form

        <h:form>
            <p:selectBooleanCheckbox value="#{testController.isInputTextRendered}">
                <p:ajax process="@form" update="@form"/>
            </p:selectBooleanCheckbox>
            <h:inputText rendered="#{testController.isInputTextRendered}"/>
            <p:commandButton process="@this" update="@form" action="#{testController.reset}"/>
        </h:form>

Controller

@Named
@ViewScoped
public class TestController implements Serializable {
    private boolean isInputTextRendered = true;
    private String inputText;

    public void reset() {
        setIsInputTextRendered(true);
        setInputText(null);
    }

    public boolean getIsInputTextRendered() {
        return isInputTextRendered;
    }

    public void setIsInputTextRendered(boolean isInputTextRendered) {
        this.isInputTextRendered = isInputTextRendered;
    }

    public String getInputText() {
        return inputText;
    }

    public void setInputText(String inputText) {
        this.inputText = inputText;
    }
}

side notes

  • it's the omnifaces @ViewScoped annotation
  • the process @form on the checkbox is necessary, because deselecting the checkbox should not reset the value of the textfield (only the button should reset it)



Aucun commentaire:

Enregistrer un commentaire