Automagically bind enum values to OptionGroup items

Hi,

I’ve a very simple enum and a bean class that has it as a member field:

public enum State{ OFFLINE(0), ONLINE(1); private int id; private State(int anId){ id = anId; } } //... public MyBean{ State state; //getters,setters and other code } Now I’m creating the corresponding Form by binding it to the bean using a BeanFieldGroup. The following code works:

MyBean bean = //some initialization here

final BeanFieldGroup<MyBean> binder = new BeanFieldGroup<MyBean>(MyBean.class);
binder.setItemDataSource(bean);
       
OptionGroup stateGroup = new OptionGroup();
stateGroup.setCaption("State");
stateGroup.addItem(State.OFFLINE);
stateGroup.addItem(State.ONLINE);
binder.bind(stateGroup, "state");
mainLayout.addComponent(stateGroup);

//other bindings

However, I found it too complicated. I’d like to follow the “buildAndBind” way, which seems simpler. Something like that:

mainLayout.addComponent(binder.buildAndBind("State","state"));

But it doesn’t work. Vaadin doesn’t know how to handle the enum in a Field. This is the error:

Caused by: com.vaadin.data.fieldgroup.FieldGroup$BindException: Unable to build a field of type com.vaadin.ui.Field for editing com.acme.State
    at com.vaadin.data.fieldgroup.FieldGroup.build(FieldGroup.java:1067)
    at com.vaadin.data.fieldgroup.FieldGroup.buildAndBind(FieldGroup.java:1039)
    at com.vaadin.data.fieldgroup.FieldGroup.buildAndBind(FieldGroup.java:1017)
    at com.vaadin.data.fieldgroup.BeanFieldGroup.buildAndBind(BeanFieldGroup.java:170)

I think the editing of enum using OptionGroup items should be the default behaviour in this case. It’s so strange that the binder can’t guess automagically the enum values by calling a simple enum.values() and putting them into an OptionGroup.

What do you think?

Found the solution by myself 1 minute after posting (Murphy rules): Simple as adding the class I want to use as an editor.

mainLayout.addComponent(binder.buildAndBind("State","state",OptionGroup.class));

Lesson learned: If you think Vaadin doesn’t have what you need, you’re probably wrong, or doing it in the wrong way.
You guys did an awesome work!

Actually, it seems FieldGroup (well, actually, DefaultFieldGroupFieldFactory that it uses as its default field factory) knows how to bind enums quite well. There’s just a minor problem:
ticket #10975
. It’s debatable whether it’s a bug or a missing feature, but the workaround is easy:

mainLayout.addComponent(binder.buildAndBind("State", "state", OptionGroup.class));

It’s not clear at all that OptionGroup would be the best “default” field for enums, anyway.

Oh yeah we can agree on that. It’s the best in my actual case but not for all, sure.
What’s important is that a default field is provided if not specified, without throwing an exception.

Another workaround could be to write an hint on the exception message, as well.