将列表<enum>绑定到vaadin中的CheckBoxGroup

时间:2017-10-21 12:27:15

标签: java vaadin

我有一个枚举:

public enum Roles {
   USER,ADMIN;
}

我的表单上有一个CheckBoxGroup:

private CheckBoxGroup<String> rolesCheckbox = new CheckBoxGroup<>("User roles");

绑定到此表单的用户类的实例有一个字段:

private List<Roles> roles;

现在我想要做的就是在为特定用户实例打开表单时检查正确的复选框。我可能必须做一些insinde binder.forField,但我真的不知道如何:

binder.forField(rolesCheckbox).bind(...

1 个答案:

答案 0 :(得分:8)

example from the Vaadin docs使用String表示简洁,但您可以轻松使用对象。假设您有Role枚举和User,如下所示:

// possible roles
public enum Role {
    ADMIN, USER, GUEST
}

// bean for binding
public class User {
    private Set<Role> roles;
    private String name;

    public User(String name, Set<Role> roles) {
        this.roles = roles;
        this.name = name;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "roles=" + roles +
                ", name='" + name + '\'' +
                '}';
    }
}

...您可以创建类似于以下内容的表单:

public class CheckboxEnumBinding extends VerticalLayout {

    public CheckboxEnumBinding() {
        // form components
        TextField nameTextField = new TextField("Name");
        CheckBoxGroup<Role> roleCheckBoxGroup = new CheckBoxGroup<>("Roles", DataProvider.ofItems(Role.values()));

        // binder setup
        Binder<User> userBinder = new Binder<>();

        // name binding
        userBinder.forField(nameTextField)
                .asRequired("Please provide a user name")
                .bind(User::getName, User::setName);

        // role binding
        userBinder.forField(roleCheckBoxGroup)
                .asRequired("Please select at least one role")
                .bind(User::getRoles, User::setRoles);

        // bind to bean
        userBinder.setBean(new User("Morfic", EnumSet.of(Role.ADMIN, Role.GUEST)));

        // simulate a save action
        Button saveButton = new Button("Save", event -> Notification.show("Saved new user info: " + userBinder.getBean()));

        // add fields to the UI
        addComponents(nameTextField, roleCheckBoxGroup, saveButton);
    }
}

<强>结果:

vaadin chekbox group binding

加分:默认情况下,Vaadin会使用枚举名称来显示值。如果你想要不同的东西,比如只用首字母大写,你可以使用ItemCaptionGenerator

// spring boot app, don't reinvent the wheel
import org.springframework.util.StringUtils;
...
roleCheckBoxGroup.setItemCaptionGenerator(role -> StringUtils.capitalize(role.name().toLowerCase()));

Vaadin item caption generator