Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global registration of field formats in Wicket

I've carefully studied Jonik's entry about customizing BigDecimal formatting in Wicket. Thanks for this excellent piece of code. Unfortunately I can't get it to work for my use case.

I want to register date formatting globally and am using the following code in the Application subclass:

@Override
protected IConverterLocator newConverterLocator() {
    ConverterLocator converterLocator = new ConverterLocator();
    converterLocator.set(Date.class, new DateConverter() {

        @Override
        public DateFormat getDateFormat(Locale ignore) {
            return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
        }

    });
    return converterLocator;
}

Then when using date fields in the web pages the code is as follows:

form.add(new TextField<Date>("dateField"));

When rendered, the date fields are showing the standard java.text.DateFormat.SHORT (02.11.11 11:59) formatting coming from the org.apache.wicket.util.convert.converter.DateConverter class instead of my custom SimpleDateFormat (02.11.2011 11:59:42).

I've checked that java.util.Date is being used throughout. Wicket version is 1.4.12.

Any ideas?

like image 746
Paul Buller Avatar asked Nov 09 '11 12:11

Paul Buller


1 Answers

I think your dateField has type java.util.Date, but actual object (loaded from database?) is e.g. java.sql.Timestamp or some other child of java.util.Date. That's why ConverterLocator chooses other converter instead of yours. The source code of the ConverterLocator has the following:

set(Date.class, new DateConverter());
set(Calendar.class, new CalendarConverter());
set(java.sql.Date.class, new SqlDateConverter());
set(java.sql.Time.class, new SqlTimeConverter());
set(java.sql.Timestamp.class, new SqlTimestampConverter());

So, you need to know the exact run-time type of your dateField and override converter for it.

like image 191
kan Avatar answered Sep 16 '22 19:09

kan