Search code examples
javavaadin8

Vaadin 8 Issue with using multiple binders on one form


I am facing an issue while binding multiple java objects on a single form in Vaadin 8.

I am not sure what I am missing here in the code.

Below is my code snippet:

public Component getSiteForm(SiteRequest requestData, LocationRequest locationRequest, boolean isReadOnly) {

    FormLayout siteForm = new FormLayout();
    siteForm.setStyleName("outlined");
    siteForm.setSizeFull();

    DefaultFormBuilder defaultSiteFormBuilder = new DefaultFormBuilder(siteForm, isReadOnly);
    final BeanValidationBinder<SiteRequest> siteBinder = new BeanValidationBinder<SiteRequest>(SiteRequest.class);
    siteBinder.setBean(requestData);

    final BeanValidationBinder<LocationRequest> locationBinder = new BeanValidationBinder<LocationRequest>(
            LocationRequest.class);
    locationBinder.setBean(locationRequest);

TextField nameField = defaultSiteFormBuilder.getTextField("Site Name");
    siteBinder.bind(nameField, "name");
    nameField.setWidth(SharkManagerConstant.DEFAULT_TEXT_FIELD_SIZE);

TextField zipcodeField = defaultSiteFormBuilder.getTextField("Zipcode");
    locationBinder.forField(zipcodeField).withNullRepresentation("560047")
            .withConverter(new StringToLongConverter("Please enter Zipcode")).bind("zipcode");
    zipcodeField.setWidth(SharkManagerConstant.DEFAULT_TEXT_FIELD_SIZE);
return siteForm;
}

SiteRequest Class is as follows:

import java.io.Serializable;
import java.sql.Time;
import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;


public class SiteRequest implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 1L;

@NotNull
@Size(min = 1, max = 40)
private String name;

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name
 *            the name to set
 */
public void setName(String name) {
    this.name = name;
}
}

LocationRequest Class is as follows:

import java.io.Serializable;

import javax.validation.constraints.NotNull;

public class LocationRequest implements Serializable {

private static final long serialVersionUID = 1L;

private Long zipcode;

public Long getZipcode() {
    return zipcode;
}

public void setZipcode(Long zipcode) {
    this.zipcode = zipcode;
}

}

I am getting ClassCastException while editing the form. Although I have put String to Long conversion.

Not sure if its a bug in Vaadin.


Solution

  • I'd guess that your interaction of withNullRepresentation and withConverter is problematic here (withNullRepresentation creates a specific converter, so that might be it). You might try reversing the order of the withConverter and withNullRepresentation calls and using a Long (the target data type) instead of a String as the null representation.