简体   繁体   中英

Binding a combo box vaadin 8

I'am trying to convert vaadin 7 code to vaadin 8 code Instead of using BeanFieldGroup vaadin 8 docs uses Binder instead to bind form fields to a class. This does not seem to work for combo box's.

I've looked for a way to use converter which does not seem to be available for combo box. As used in binding data to form in the vaadin documentation here

For one field the converter worked:

binder.forField(age).withConverter(
                    new 
StringToIntegerConverter("Must enter a number")).bind(
                    Student::getAge, 
Student::setAge);

But for a combo box I'am unsure how this will work.

ComboBox<String> gender = new ComboBox<String>("Gender");

Binder binder = new Binder<Student>(Student.class);

binder.bind(gender, Student::getGender, Student::setGender);

Which I know will not work is there a way to write a converter for a combo box or should another way be used altogether.

You mentioned in a comment that the gender field in your Student object is actually an Enum and not a String.

Your mistake was that you defined the ComboBox with type String instead of your Gender enum.

Assuming your gender enum class is called Gender , this will work:

ComboBox<Gender> gender = new ComboBox<Gender>("Gender");
Binder binder = new Binder<Student>(Student.class);
binder.bind(gender, Student::getGender, Student::setGender);

You can add an ItemLabelGenerator to the ComboBox to define how your Gender enum should be displayed. By default it will use toString() of the class. But you could use it to build Vaadin Components for example if you want. see how it is done in the documentation ).

I have found that in vaadin 8 uses bindInstanceFields to bind form data to a class.

Binder binder = new Binder<Student>(Student.class);

binder.bindInstanceFields(this);
binder.readBean(student);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM