FieldGroup using switch instead of checkbox

Hello,
I am using a FieldGroup to create from an object, containing multiple boolean values, a form. It is working as expected, but I would like to replace the checkbox by the touchkit switch, because I use the form in a mobile application.
Can someone give me a short description how can I achieve this? I already studied the FieldGroup class, but without success.

If I try the following binding:

for(Object propertyId : item.getItemPropertyIds()) { try { this.addComponent(binder.buildAndBind(Lang.getString("privacy."+propertyId, getLocale()), propertyId, Switch.class)); } catch(BindException e) { e.printStackTrace(); } } I get the following exception:

Unable to build a field of type com.vaadin.addon.touchkit.ui.Switch for editing java.lang.Boolean which I do not understand, because the switch only allows boolean values.

Thanks,
Florian

Hi Florian,

The problem is that FieldGroup does not by default know how to create an instance of a Switch. This is pretty easy to fix, however, by setting a custom field factory when you create the FieldGroup:

binder.setFieldFactory(new DefaultFieldGroupFieldFactory() {
    @Override
    protected <T extends Field> T createBooleanField(Class<T> fieldType) {
        if(fieldType.isAssignableFrom(Switch.class)) {
            Switch sw = new Switch();
            sw.setImmediate(true); // or false, depending; by default CheckBox is set to immediate
            return (T) sw;
         }
         return super.createBooleanField(fieldType);
    }
}

Alternatively, you can create the instances yourself in the loop and bind them:

Switch sw = new Switch(Lang.getString("privacy."+propertyId, getLocale()));
binder.bind(sw, propertyId);
addComponent(sw);

Thank you for your help, I will use your first suggestion. In the meantime I realized it using the Mexico method: I iterate manually through the instance, hide the checkbox and added a swith manually with a value change listener, which changed the value of the checkbox.
The only thing I do not understand is that the only difference (based on the source code for the Switch) between the checkbox and the switch ist the stylename (actually the switch only extends the Checkbox by setting the style to “switch”). Therefore if I add this stylename to the checkbox the box should be displayed as switch but it doe not. This is really a littel bit strange to me.

However thanks for your help,
Florian

It’s because the client-side implementation is quite different. It has separate
widget
and
connector
classes.

Hi having the same problem, but want the boolean to be used as a combobox instead of a checkbox, followed a similar approach but getting compiler errors?