Wicket checkbox that automatically submits its changed value to domain object

Jonik picture Jonik · Nov 24, 2010 · Viewed 17.6k times · Source

What's the cleanest way I can make a checkbox automatically submit the form it belongs to in Wicket? I don't want to include a submit button at all. The checkbox is backed by a boolean field in a domain object ("Account" in this case).

Simplified example with irrelevant parts omitted:

EntityModel<Account> accModel = new EntityModel<Account>(Account.class, id);

PropertyModel<Boolean> model = new PropertyModel<Boolean>(accModel, "enabled");
CheckBox checkBox = new CheckBox("cb", model);
Form form = new Form("form");
form.add(checkBox);
add(form);

HTML:

<form wicket:id="form" id="form" action="">
    <input wicket:id="cb" type="checkbox" />
</form>

Edit: To clarify, my goal is just to change the domain object's field (-> value in database too) when the checkbox is toggled. Any (clean, easy) way to achieve that would be fine. (I'm not sure if you actually need the form for this.)

Answer

Jonik picture Jonik · Nov 24, 2010

Just overriding wantOnSelectionChangedNotifications() for the checkbox—even without overriding onSelectionChanged()—seems to do what I want.

This way you don't need the form on Java side, so the above code would become:

EntityModel<Account> accModel = new EntityModel<Account>(Account.class, id);

add(new CheckBox("cb", new PropertyModel<Boolean>(accModel, "enabled")){
    protected boolean wantOnSelectionChangedNotifications() {
        return true;
    }
});

Feel free to add better solutions, or a better explanation of what's going on with this approach!

Edit: On closer inspection, I guess the method's Javadoc makes it reasonably clear why this does what I wanted (emphasis mine):

If true, a roundtrip will be generated with each selection change, resulting in the model being updated (of just this component) and onSelectionChanged being called.