如何从Vaadin RadioButtonGroup国家/地区绑定到国家/地区 DAO对象?国家/地区为枚举, DateField(vaadin)为 LocalDate(DAO)
public class Person {
@Id
String id;
LocalDate dateBorn;
Country country;
......
public class PersonFormUI extends GridLayout {
RadioButtonGroup<Country> country;
DateField dateBorn;
........
public enum Country {
EN, DE, IT }
使用此绑定所有字段都绑定并运行良好,但如何使用转换器绑定枚举和日期?
binder.bindInstanceFields(this);
binder.setBean(personDAO);
答案 0 :(得分:0)
如果我可以在直接编写代码之前添加一些建议:
FormLayout
ComboBox
代替RadioButtonGroup
来显示国家/地区,因为它占用的空间更少,并且您还可以通过输入来快速找到所需内容。但如果你真的想要收音机,请用RadioButtonGroup<Country> countries = new RadioButtonGroup<>("Country", DataProvider.ofItems(Country.values()));
您可以在下面找到基于上述建议和Vaadin 8.3.1的绑定样本。我认为没有必要进行任何转换,因为框架会为您处理。
我做的唯一额外的事情是为组合添加ItemCaptionGenerator
以显示完整的国家/地区名称而不是使用枚举名称的默认名称(同样的内容可以与RadioButtonGroup
一起使用)。
<强>代码:强>
public class PersonForm extends FormLayout {
public PersonForm() {
// form components
DateField birthDate = new DateField("Birth date");
ComboBox<Country> countries = new ComboBox<>("Country", Arrays.asList(Country.values()));
// use full country name instead of ugly Enum name
countries.setItemCaptionGenerator(Country::getFullName);
// do not allow the user to select "nothing"
countries.setEmptySelectionAllowed(false);
// binder setup
Binder<Person> userBinder = new Binder<>();
// birth date binding
userBinder.forField(birthDate)
.asRequired("Please provide a birth date")
.bind(Person::getDateBorn, Person::setDateBorn);
// country binding
userBinder.forField(countries)
.asRequired("Please select the country of residence")
.bind(Person::getCountry, Person::setCountry);
// bind to bean with some existing value (eg, loaded from DB for editing)
userBinder.setBean(new Person(LocalDate.now(), Country.RO));
// simulate a save action
Button saveButton = new Button("Save", event -> Notification.show("Saved new user info: " + userBinder.getBean()));
// add fields to the UI
addComponents(birthDate, countries, saveButton);
}
// beans
public class Person {
private LocalDate dateBorn;
private Country country;
public Person(LocalDate dateBorn, Country country) {
this.dateBorn = dateBorn;
this.country = country;
}
public LocalDate getDateBorn() {
return dateBorn;
}
public void setDateBorn(LocalDate dateBorn) {
this.dateBorn = dateBorn;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
@Override
public String toString() {
return "Person{" +
"dateBorn=" + dateBorn +
", country=" + country +
'}';
}
}
public enum Country {
RO("Romania"), DE("Deutschland"), IT("Italy");
private String fullName;
Country(String fullName) {
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
}
}
<强>结果:强>
您可以更进一步,根据活页夹状态禁用该按钮(可能您希望使用相同的表单添加没有初始值的新人):
// disable saving until all required data is available
userBinder.addStatusChangeListener(event -> saveButton.setEnabled(userBinder.isValid()));`
<强>结果:强>