objectprogr
objectprogr

Reputation: 89

Vaadin 8 convert String to Float

i have 3 TextFiled, one which save String to database, and 2 which should save FLoat to database. When i run my application, i have this error:

Property type 'java.lang.Float' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

This is my code:

@SpringComponent
@UIScope
public class FuelEditor extends VerticalLayout{
private final FuelReposiotry fuelRepository;

private Fuel fuel;
/* Fields to edit properties in Customer entity */
TextField date = new TextField("Data");
TextField price = new TextField("Cena");
TextField amount = new TextField("Kwota tankowania");

/* Action buttons */
Button save = new Button("Save", FontAwesome.SAVE);
Button cancel = new Button("Cancel");
Button delete = new Button("Delete", FontAwesome.TRASH_O);
CssLayout actions = new CssLayout(save, cancel, delete);

Binder<Fuel> binder = new Binder<>(Fuel.class);

@Autowired
public FuelEditor(FuelReposiotry fuelReposiotry) {
    this.fuelRepository = fuelReposiotry;

    addComponents(date, price, amount, actions);
    // bind using naming convention
    binder.bindInstanceFields(this);

    // Configure and style components
    setSpacing(true);
    actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    save.setStyleName(ValoTheme.BUTTON_PRIMARY);
    save.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    // wire action buttons to save, delete and reset
    save.addClickListener(e -> fuelReposiotry.save(fuel));
    delete.addClickListener(e -> fuelReposiotry.delete(fuel));
    cancel.addClickListener(e -> editFuel(fuel));
    setVisible(false);
}

How can I convert String to Float? I trying with import com.vaadin.data.util.converter.StringToIntegerConverter;, but in vaadin 8 I cant to use converter.

Upvotes: 2

Views: 590

Answers (1)

Erik Lumme
Erik Lumme

Reputation: 5342

You should be able to use a StringToFloatConverter, but you have to bind those fields manually:

@SpringComponent
@UIScope
public class FuelEditor extends VerticalLayout{

TextField date = new TextField("Data");
TextField price = new TextField("Cena");
TextField amount = new TextField("Kwota tankowania");

Binder<Fuel> binder = new Binder<>(Fuel.class);

@Autowired
public FuelEditor(FuelReposiotry fuelReposiotry) {

    // Bind float fields manually
    binder.forField(price)
            .withConverter(new StringToFloatConverter("Value must be a float"))
            .bind(Fuel::getPrice, Fuel::setPrice);
    binder.forField(amount)
            .withConverter(new StringToFloatConverter("Value must be a float"))
            .bind(Fuel::getAmount, Fuel::setAmount);
    // bind the last using naming convention
    binder.bindInstanceFields(this);
}

Upvotes: 4

Related Questions