Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wicket checkbox that automatically submits its changed value to domain object

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.)

like image 623
Jonik Avatar asked Nov 24 '10 09:11

Jonik


2 Answers

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.

like image 145
Jonik Avatar answered Nov 08 '22 08:11

Jonik


While this may work, you are far better off using AjaxCheckBox. An anonymous subclass can be wired to receive events immediately as well as make changes to the UI outside the checkbox itself.

final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); 
final EntityModel<Account> accModel = new EntityModel<Account>(Account.class, id); 
wmc.setVisible(false); 
wmc.setOutputMarkupPlaceholderTag(true);
form.add(new AjaxCheckBox("cb", new PropertyModel<Boolean>(accModel, "enabled")) {
    @Override
    protected void onUpdate(AjaxRequestTarget target) {
        wmc.setVisible(accModel.isEnabled());
        target.addComponent(wmc);
        // .. more code to write the entity
    }
});

In this contrived example, the WebMarkupContainer would be made visible in sync with the value of the checkbox.

like image 29
Brian Topping Avatar answered Nov 08 '22 08:11

Brian Topping