4.2.2.3.3. Example of a Custom Datatype

Let us consider the implementation of a custom GeoCoordinateDatatype, intended for the attributes storing geographical coordinates.

First, we need to create a class in the global module:

public class GeoCoordinateDatatype extends DoubleDatatype {

    public static final String NAME = "geocoordinate";

    // the format is the same for all locales but may differ in decimal points
    public static final String FORMAT = "#0.000000";

    public GeoCoordinateDatatype(Element element) {
        super(element);
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public String format(Double value, Locale locale) {
        if (value == null)
            return "";
        FormatStrings formatStrings = Datatypes.getFormatStrings(locale);
        if (formatStrings == null)
            return format(value); // FormatStrings are not defined for locales, so formatting is made according to datatypes.xml file

        NumberFormat format = new DecimalFormat(FORMAT, formatStrings.getFormatSymbols());
        return format.format(value);
    }

    @Override
    public Double parse(String value, Locale locale) throws ParseException {
        if (StringUtils.isBlank(value))
            return null;
        FormatStrings formatStrings = Datatypes.getFormatStrings(locale);
        if (formatStrings == null)
            return parse(value); // FormatStrings are not defined for locales, so parsing is made according to datatypes.xml file

        NumberFormat format = new DecimalFormat(FORMAT, formatStrings.getFormatSymbols());
        return parse(value, format).doubleValue();
    }
}

Next, we create datatypes.xml file in the root of the global module src directory in the application project and copy contents from /com/haulmont/chile/core/datatypes/datatypes.xml file located in global module of *cuba *base project. Then add registration of the new type to it:

<datatypes>

    <datatype class="com.sample.sales.entity.GeoCoordinateDatatype"
              format="#0.000000" decimalSeparator="." groupingSeparator=""/>
    ...

Finally we specify new datatype for the required attributes:

@MetaProperty(datatype = GeoCoordinateDatatype.NAME)
@Column(name = "LATITUDE")
private Double latitude;

After the above listed operations are completed, latitude attribute will be displayed in the desired format throughout the application.