Wicket checkbox that automatically submits its changed value to domain object

∥☆過路亽.° 提交于 2019-12-03 06:30:29

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!