- VolkomenJuist.nl - http://www.volkomenjuist.nl/blog -

Wicket’s FormComponent setType

If you are creating a form for your application you might need some validation on components before submitting. Wicket has some methods (e.g setRequired(true)) which can help you with that. In this article I will show you the setType method. This method will prevent you to submit the form when e.g. the input field is not filled in correctly. An example could be when your users have to fill in a double as number. If the user fills in something else it will show a warning in the feedbackpanel. See java example below how to deal with this.

public HomePage(final PageParameters parameters) {

Form form = new Form("form", new CompoundPropertyModel(this));
add(form);

TextField tf = new TextField("doubleValue");
tf.setType(Double.class);
tf.setRequired(true);
form.add(tf);
form.add(new Button("bt1") {
 private static final long serialVersionUID = -1179492663996608643L;

 @Override
 public void onSubmit() {
  super.onSubmit();

  System.out.println("Form submitted");
}});

add(new FeedbackPanel("feedback").setOutputMarkupId(true));
}

public double getDoubleValue(){
 return m_value;
}

public void setDoubleValue(double value) {
 m_value = value;
} 

Please note the setType(Double.class) (line 7). This will prevent the user to submit the form when no double is filled in. Simply it doesn’t goes into the onSubmit() method. By default it will use the String type. This type will also be used when updating the model for this component.  

A shorter notation (instead of line 6 and 7):

TextField tf = new TextField("doubleValue", Double.class);

Corresponding HTML:

<form wicket:id="form">
<input type="text" wicket:id="tf1"/>
<input type="submit" wicket:id="bt1"/>
</form>
<div wicket:id="feedback"/>
Buffer [1]
[2]