Tkingovr Tkingovr - 1 month ago 15
Java Question

Toggle TextField required/not required when checkbox checked

I have a text field which I want to toggle as a required field or not based on if a checkbox is checked. I can't get the ValueChangeEventListener to play nice.

This is what I have so far:

private TextField myTextField = new TextField("Name");
myTextField.setRequired(true);

private CheckBox myCheckBox;
myCheckBox = createCheckBox();


private CheckBox createCheckbox() {
CheckBox checkBox = new CheckBox("My checkbox");
checkBox.setImmediate(true);
checkBox.addValueChangeListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
toggleRequired();
}
});
return checkBox;
}


private void toggleRequired() {
if (myCheckBox.getValue() != true) {
myTextField.setRequired(false);
} else {
myTextField.setRequired(true)
}
}


The valueChangeListener gets fired way too many times going from true to false back to true. Not sure what I'm doing wrong here and would really appreciate some help.

Thank you

Answer

Ok I figured it out! It was a very easy solution all I had to change was

 checkBox.addValueChangeListener(new CheckBox.ValueChangeListener() {});

I was referencing some the following properties class instead:

properties.ValueChangeListener();