Flagging a form field as "required" is the most common kind of validation. In most cases, this can be specified statically as follows:
add(new TextField("foo").setRequired(true));
In some cases, however, whether or not the field is required cannot be determined when the form is created. Like many properties in Wicket, we can override the property setter (isRequired
, in this case) to defer the evaluation of the property until the last possible moment:
add(new TextField("foo") { public boolean isRequired() { // return true if the field is required } }
That's the simple part. Unfortunately, implementing isRequired
can be tricky, since it's called very early in the form processing cycle, before values are converted and models are updated. Below we provide a few recipes that cover some common scenarios.
Submit Button
In this recipe, the field is in a form with multiple submit buttons. We only want to require the field when one of the buttons is clicked:
Button submit = new Button("submit") { public void onSubmit() { // handle form submission } } form.add(submit); TextField foo = new TextField("foo") { public boolean isRequired() { Form form = (Form) findParent(Form.class); return form.getRootForm().findSubmittingButton() == submitButton; } } form.add(foo);
Note the call to getRootForm
. Technically, this is only required in nested forms.
If you would like to bypass validation altogether you can do so by:
new Button("submit").setDefaultFormProcessing(false);
CheckBox
In this recipe, the field is only required when a checkbox on the form is checked:
final CheckBox checkBox = new CheckBox("cb"); form.add(checkBox); TextField foo = new TextField("foo") { public boolean isRequired() { return Strings.isTrue(checkBox.getValue()); } } form.add(foo);
Radio Button
Here the field is only required when a particular radio button on the form is selected:
final RadioGroup radioGroup = new RadioGroup("radioGroup"); form.add(radioGroup); final Radio radio1 = new Radio("radio1"); radioGroup.add(radio1); TextField foo = new TextField("foo") { public boolean isRequired() { return Strings.isEqual(radioGroup.getInput(), radio1.getValue()); } } form.add(foo);