How to bind DateField with Vaadin8 Binder

I’ve successfully migrated Vaadin 7 code to Vaadin8 for TextField using your examples

// With explicit callback interface instances
binder.bind(nameField,
  new ValueProvider<Person, String>() {
    @Override
    public String apply(Person person) {
      return person.getName();
    }
  },
  new Setter<Person, String>() {
    @Override
    public void accept(Person person, String name) {
      person.setName(name);
    }
  });

Is there a way to bind DateField objects ?
Thanks,
Ivan

Yes, but since the new
DateField
s (and
DateTimeField
s, there are now two separate classes) use
LocalDate/LocalDateTime
instead of
Date
, you have provide a converter. See eg.
https://stackoverflow.com/questions/19431234/converting-between-java-time-localdatetime-and-java-util-date




So, it would look like this:

binder.bind(dateTimeField, 
 new ValueProvider<Person, LocalDateTime>() {
  @Override
  public LocalDateTime apply(Person person) {
   return person.getDate() == null ? null :
    LocalDateTime.ofInstant(person.getDate().toInstant(), ZoneId.systemDefault());
  }
 }, 
 new Setter<Person, LocalDateTime>() {
  @Override
  public void accept(Person person, LocalDateDime ldt) {
   Date toSet = ldt == null ? null : Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());   
   person.setDate(toSet);
  }
 });

Thank you very much! It works :slight_smile: Have a nice day!

BTW, you can use lambda expressions and make the code a one-liner:

binder.bind(nameField, Person::getName, Person::setName); Also, you can use the provided
LocalDateTimeToDateConverter
which is almost the same Piotr implemented in his answer :slight_smile: Here’s how:

binder.forField(dateTimeField)
        .withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault()))
        .bind(Person::getDate, Person::setDate);

hello i think in your entity you use Date as class field right?

I resolve this problem to change Date to LocalDate or LocalDateTime object.

If you use hibernate then use hibernate.core liblary which supports LocalDate and LocalDateTime. Vaadin 8 work better with java 8. If you still need to use Date as your object you need to use converter to

Alejandro Duarte:
BTW, you can use lambda expressions and make the code a one-liner:

binder.bind(nameField, Person::getName, Person::setName);

Also, you can use the provided LocalDateTimeToDateConverter which is almost the same Piotr implemented in his answer :slight_smile: Here’s how:

binder.forField(dateTimeField)
        .withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault()))
        .bind(Person::getDate, Person::setDate);

can i ask something?
i want to insert from my datefield into database. how can i get the value from my datefield?.
thanks

Adiva, you can call datefield.getValue. If you are using a Binder you can get the value directly from the bean (e.g. person.getDate()).