Binding a bigdecimal to a field in Vaadin

Hey everyone,

I want to bind a BigDecimal to a field in Vaadin, preferably a numberfield.
I tried this so far using a textfield with a converter and to bind it to a numberfield.
Could anyone provide information or an example on how to do this?

Here is a simple example of what I’m trying but failing to do:

@Id("numberfield")
private NumberField numberfield;

Binder<testM> binder = new Binder<>(testM.class);
binder.bind(numberfield, testM::getTest, testM::setTest);

Or using a textfield:

@Id("texttest")
private TextField texttest;

Binder<testM> binder = new Binder<>(testM.class);
binder.forField(tttt).withConverter(new StringToBigDecimalConverter("")).bind("");
binder.bind(texttest, testM::getTest, testM::setTest);

Hi Sjoerd

You almost got it working with the TextField. Here is a fully working way to bind a TextField with a BigDecimal value:

binder.forField(texttest)
    .withConverter(new StringToBigDecimalConverter(""))
	.bind(testM::getTest, testM::setTest);

If you want to use a NumberField for this, then you will have to implement a DoubleToBigDecimalConverter, as this is not provided by vaadin. Here is how it could look:

public class DoubleToBigDecimalConverter implements Converter<Double, BigDecimal> {
    @Override
    public Result<BigDecimal> convertToModel(Double presentation, ValueContext valueContext) {
        return Result.ok(BigDecimal.valueOf(presentation));
    }

    @Override
    public Double convertToPresentation(BigDecimal model, ValueContext valueContext) {
        return model.doubleValue();
    }
}

Now having this converter, you can bind your NumberField like so:

binder.forField(numberField)
    .withConverter(new DoubleToBigDecimalConverter())
	.bind(testM::getTest, testM::setTest);

Hi Kasper,

Thank you for your reply! This makes life much easier!

Thank you