Wicket checkbox that automatically submits its changed value to domain object

我怕爱的太早我们不能终老 提交于 2020-01-01 02:45:10

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4265432/wicket-checkbox-that-automatically-submits-its-changed-value-to-domain-object

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