Search code examples
javavaadin8

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.


Solution

  • 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<Student> binder = new Binder<Student>(Student.class);
    binder.bind(gender, Student::getGender, Student::setGender);
    

    You can add an ItemLabelGenerator to the ComboBox to define how the selected Gender value should be displayed (and Renderer, which will control how the items in the dropdown will look). By default it will use toString() of the class, both for itemLabelGenerator and for renderer. But you could use the Renderer to build Vaadin Components for example if you want. see how it is done in the ComboBox documentation).

    The selected value can only be displayed as a String. If you want to let it be displayed as a Vaadin Component instead, you could use a Select component instead. Select documentation.