Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

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 getter (isRequired, in this case) to defer the evaluation of the property until the last possible moment:

...

Code Block
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() == submitButtonbutton;
    }
}
form.add(foo);

Note the call to getRootForm. Technically, this is only required in nested forms.

...

Code Block
new Button("submit").setDefaultFormProcessing(false);

Validating just the button-press

Simply add a validator to the button which checks if it was pressed:

Code Block

button.add(new IValidator<String>() {
        @Override
        public void validate(IValidatable<String> validatable) {
          if (button.getForm().findSubmittingButton() == button) {
            // ... do your test here
            if (errorFound) {
              ValidationError error = new ValidationError().addMessageKey("errorFound_button");
              error.setVariables(Collections.singletonMap("parameter", (Object) "value"));
              validatable.error(error);
            } 
          }
        }
      });

Alternative Approach

Another approach to enabling validation based on which submit button was used is to take over the form processing workflow as follows.

...

Occasionally, you may want the forms to be truly independent, i.e. you want the parent form to not validate and submit the child form. This is easily done by overriding isEnabled() on the child form as follows:

Code Block

class InternalForm<T> extends Form<T> implements IFormVisitorParticipant {
    public InternalForm(String name) {
        super(name);
    }

    public InternalForm(String name, IModel<T> model) {
        super(name, model);
Code Block

Form nestedForm = new Form("nestedForm") {
    @Override}

    public boolean isEnabledprocessChildren() {
        IFormSubmittingComponent returnsubmitter = getRootForm().findSubmittingButton();
        if (submitter == null)
            return false;
        
        return submitter.getForm() == this;
    }
}

Form nestedForm = new InternalForm("nestedForm");