Change NumberFormat for a BigDecimal attribute at runtime

Hi,

In a Jmix 2.x project, is it possible to change the number of decimal places (NumberFormat) for a BigDecimal attribute at runtime?

We would like to solve the following case:
We have an entity in which there is a Quantity attribute of type BigDecimal and a reference to a Unit entity (e.g. piece, meter, kilogram, hour etc.) in which you can specify how many decimal places can be entered in the Quantity field for the given Unit. During editing, if the user changes the selected Unit, the format of the number that can be entered in the Quantity field should be changed accordingly.

Thanks,
Peter

Hi Peter,

First, unbound the field from data container and set datatype to the standard decimal:

<textField id="amountField" datatype="decimal"/>

In the controller, create a datatype with the required parameters and manually read/write the field value:

@ViewComponent
private TypedTextField<BigDecimal> amountField;
@Autowired
private FormatStringsRegistry formatStringsRegistry;

@Subscribe
public void onBeforeShow(final BeforeShowEvent event) {
    AdaptiveNumberDatatype adaptiveNumberDatatype = new AdaptiveNumberDatatype(
            BigDecimal.class,
            "#,##0.000",
            ".",
            ",",
            formatStringsRegistry
    );
    amountField.setDatatype((Datatype) adaptiveNumberDatatype);
    amountField.setTypedValue(getEditedEntity().getAmount());
}

@Subscribe("amountField")
public void onAmountFieldTypedValueChange(final SupportsTypedValue.TypedValueChangeEvent<TypedTextField<BigDecimal>, BigDecimal> event) {
    getEditedEntity().setAmount(event.getValue());
}

AdaptiveNumberDatatype is defined in the framework for the entity attributes having @NumberFormat annotation. You can also create your own implementation similarly.

Regards,
Konstantin

1 Like

Hi Konstantin,

Perfect, thank you. :slight_smile:

Peter