Fork me on GitHub
Showing posts with label joda time. Show all posts
Showing posts with label joda time. Show all posts

10 Jul 2010

Rendering Grails Joda-Time date inputs cross browser with HTML5, jQuery and Modernizr

Yesterday I released a new version of the Grails Joda-Time plugin that includes support for the various new date and time input types in the HTML5 standard. Right now only Opera supports these types with proper date-picker type controls, the other browsers just render them as text inputs. However this doesn’t mean you can’t or shouldn’t start using them right away. There’s a very handy JavaScript library called Modernizr that you can use to detect the features supported by the client’s browser and render alternatives using script. In this post I’m going to walk through how to combine the Joda-Time plugin, Modernizr and the jQuery datepicker to render an HTML5 date input field that will bind to a LocalDate property on a domain object.

Install the Joda-Time plugin

If you don’t currently have version 1.1+ of the Joda-Time plugin installed, run grails install-plugin joda-time.

Once the plugin is installed you will need to enable HTML5 support so that data binding will use the HTML5 date/time formats. Simply add the following to your Config.groovy

jodatime.format.html5 = true

Create a domain class with a LocalDate property

For this example I’ll create a simple domain class representing a person:

import org.joda.time.*
import org.joda.time.contrib.hibernate.*

class Person {
    String name
    LocalDate birthdate
    static mapping = {
        birthdate type: PersistentLocalDate
    }
}

If you have default mappings set up (which the Joda-Time plugin will attempt to do for you when it installs) then you can omit the mapping block but I’ve included it for completeness.

Execute grails generate-all Person to create a controller and scaffolded views for the Person class. Finally change the create.gsp and edit.gsp files to use an HTML5 input instead of the standard Grails date picker tag. Replace the <g:datePicker name="birthdate"… with this:

<joda:dateField name="birthdate" value="${personInstance.birthdate}"/>

In the unlikely event that all your site’s visitors are using Opera then your work is done at this point. However right now anyone using another browser will have to type in the birthdate value in the correct format in order to get the forms to submit properly which isn’t the friendliest user experience.

Install jQuery and jQuery-UI

You can include jQuery and jQuery-UI by simply downloading the JavaScript files into your app, or linking to them on Google. Alternatively you can use the Grails plugins. If you want to go the plugin route this is what you will need to do. First install the plugins:

grails install-plugin jquery-ui

The jQuery plugin is installed automatically by the jQuery-UI plugin.

Then you will need to add the libraries to your SiteMesh template (or you could include it just on the relevant pages, it doesn’t matter). Add the following in the head section:

<g:javascript library="jquery" plugin="jquery"/>
<jqui:resources components="datepicker" mode="normal" />

Install Modernizr

Download Modernizr and put it in web-app/js/modernizr. You can link to the script direct from there or define a library by adding this to BootStrap.groovy:

import org.codehaus.groovy.grails.plugins.web.taglib.JavascriptTagLib

class BootStrap {
    def init = { servletContext ->
         JavascriptTagLib.LIBRARY_MAPPINGS.modernizr = ["modernizr/modernizr-1.5.min"]
    }

Then include Modernizr in your SiteMesh template by adding the following in the head section:

<g:javascript library="modernizr"/>

To get Modernizr to work its magic you should add a class="no-js" to the html element at the top of your SiteMesh template. Modernizr will replace this when the document loads with a whole bunch of classes that it uses to detect the various features supported by the browser.

Bind the jQuery-UI datepicker to the field

The last step is to ensure that any time a user hits the page with a browser that doesn’t support a native widget for the date input type they get a jQuery datepicker instead. To do this create a JavaScript file and link to it from your SiteMesh template or the pages using date inputs. The script simply needs to contain the following code:

$(document).ready(function() {
    if (!Modernizr.inputtypes.date) {
        $("input[type=date]").datepicker({dateFormat: $.datepicker.W3C});
    }
});

What this does is create a function that runs on page load that uses Modernizr to determine if the date input type is supported and if not initialises a jQuery-UI datepicker for every <input type="date"… found in the page. The dateFormat argument ensures the jQuery widget will update the input with the correct date format when a value is selected.

It’s that simple. Now the create and edit person pages will use the native date input widget when the visitor’s browser supports one and the jQuery widget when it doesn’t.

So how does it look? Here's a screenshot of the page in Firefox when a visitor has focused the date input:

Here's the same thing rendered in Opera using the native datepicker widget (yes, you could be forgiven for thinking the jQuery version is prettier):

With a little adaptation the same thing can be done for the other input types; month, week, time, datetime and datetime-local. Of those month should work perfectly by adding this to your script:

if (!Modernizr.inputtypes.month) {
    $("input[type=month]").datepicker({dateFormat: 'yy-mm');
}

Other types would require different widgets to enable users to input the time portion of the value. There are several jQuery based options available. Of course, instead of jQuery you could use YUI, script.aculo.us or any other date/time widgets. I’ve gone with jQuery because I’m familiar with it and the initialisation is beautifully simple even if you’ve got a number of different inputs on a page.

24 Jun 2010

Defaulting Joda Time Hibernate Types with Grails

Grails 1.2 added the ability to define default Hibernate mappings that apply to all GORM classes. It turns out this is incredibly useful if you're using Joda-Time types instead of java.util.Date in your domain objects. Previously you had to specify the Hibernate user type for every single field, like this:
import org.joda.time.*
import org.joda.time.contrib.hibernate.*

DateTime dateCreated
DateTime lastUpdated
LocalDate birthday

static mapping = {
    dateCreated type: PersistentDateTime
    lastUpdated type: PersistentDateTime
    birthday type: PersistentLocalDate
}
Now you can just add this to your Config.groovy once and do away with the type mappings in the individual classes:
grails.gorm.default.mapping = {
    "user-type" type: PersistentDateTime, class: DateTime
    "user-type" type: PersistentLocalDate, class: LocalDate
}
Correction: I had previously posted that the method call in the default mapping DSL could be anything, but on further investigation it turns out it has to be user-type. Apologies for the error.

I'll look into the possibility of the Joda-Time plugin doing this itself to make things even easier.

12 Aug 2009

JSON Rendering Your Classes

It turns out adding custom JSON renderers for your own types to Grails is really easy. Since I habitually use Joda Time instead of the horrible java.util.Date and even more horrible java.util.Calendar I need to be able to render classes such as Joda's DateTime as JSON so that domain objects with fields of those types will convert properly.

Implementing a renderer for a type is as easy as this: DateTimeMarshaller.java. After that all that's required is to register the new renderer in BootStrap.groovy or some other appropriate spot with:

grails.converters.JSON.registerObjectMarshaller new DateTimeMarshaller()

I'll be adding this to the next release of the Joda Time Plugin so that it's completely transparent.

Update: Actually it's even easier than I thought. This being Groovy you can just use closures like so:

JSON.registerObjectMarshaller(DateTime) {
return it?.toString("yyyy-MM-dd'T'HH:mm:ss'Z'")
}

Update: This is now built in to version 0.5 of the Joda Time Plugin.

18 Jun 2009

Joda Time Auto-Timestamping Issue on Grails 1.1.1

I've not upgraded most of my code to Grails 1.1.1 yet so I hadn't noticed this problem until it was brought to my attention by Manuel Vio on the grails-user mailing list.

I raised a bug a few days ago around the fact that GORM identifies Joda Time types (and presumably any non-default property type) as a one-to-one association. Up to now the only problem this caused me was that it means the Joda Time plugin has to do some slightly hacky tricks in the scaffolding templates to prevent crashes when Grails tries to render the properties as though they were associated domain instances only to find they have no id property. However, on Grails 1.1.1 the bug is causing a nasty failure on auto-timestamping.

Under Grails 1.1 you can use a Joda DateTime for an auto-timestamped fields:

DateTime dateCreated
DateTime lastUpdated

static mapping = {
dateCreated type: PersistentDateTime
lastUpdated type: PersistentDateTime
}

These behave exactly like the regular Date fields with those names, i.e. they're set automatically on save and update. In Grails 1.1.1 the same class will fail on save with a GroovyRuntimeException Could not find matching constructor for: java.lang.Object(java.lang.Long).

There is a (somewhat strange) workaround - declare the timestamped fields as non-lazy!

DateTime dateCreated
DateTime lastUpdated

static mapping = {
dateCreated type: PersistentDateTime, lazy: false
lastUpdated type: PersistentDateTime, lazy: false
}

Digging into the Grails code a little I found that association properties have their getter wrapped in a lazy-loading proxy. Since GORM thinks Joda Time properties are associations, this happens to them. The auto-timestamping code initialises the properties using property.getType().newInstance(System.currentTimeMillis()). Unfortunately, because property is actually the lazy-load proxy rather than the real property property.getType() returns Object.

31 Mar 2009

Joda-Time and Grails Auto-Timestamping

The Joda-Time Plugin docs state that Grails' auto-timestamping works with Joda-Time properties which is the case. However, when testing it can be useful to take advantage of Joda Time's DateTimeUtils class to mock the current time. This enables you to have new DateTime objects, for example, use a predictable timestamp. Unfortunately it doesn't play nicely with Grails' auto-timestamping which under the covers uses System.currentTimeMillis(). There are a couple of solutions to this. You can disable the auto-timestamping and define your own beforeInsert event which enables you to use DateTimeUtils.setCurrentMillisFixed. For example:

static mapping = {
autoTimestamp false
}

def beforeInsert = {
dateCreated = new DateTime()
}

The other option would be to mock out the value returned by System.currentTimeMillis(). This has the advantage of meaning you don't have to add code to your domain class to enable tests to work, but on the other hand it's all to easy to have such meta class modifications leak from test to test by not being torn down properly.

On a related note the next release of the Joda-Time plugin will bind additional methods to DateTimeUtils to scope mocking of the current timestamp, for example:

DateTimeUtils.withCurrentMillisFixed(aLong) {
// do some stuff that requires a mocked current time
}

No more forgetting to call DateTimeUtils.setCurrentMillisSystem() in your tearDown method!

3 Mar 2009

Persisting DateTime with zone information

I was stuck a while ago trying to figure out how to map PersistentDateTimeTZ in a GORM class. It's an implementation of Hibernate's UserType interface that persists a Joda DateTime value using 2 columns - one for the actual timestamp and one for the time zone. The DateTime class contains time zone information but a SQL timestamp column is time zone agnostic so you can lose data when the value is saved (the same exact problem exists when persisting java.util.Date values).

I could never figure out how to map the user type to my domain class property correctly. Just doing:

static mapping = {
dateTimeProperty type: PersistentDateTimeTZ
}

Failed with:

org.hibernate.MappingException: property mapping has wrong number of columns.

I seem to remember someone on the Grails mailing list suggesting I tried treating the value as an embedded type. That also didn't work as GORM embedded types have to be Groovy classes in grails-app/domain and PersistentDateTimeTZ is written in Java and lives in a library jar.

I finally found the solution in the 2nd Edition of The Definitive Guide to Grails (which I can't recommend enough, by the way). The trick is to pass a closure specifying the two columns to the property definition in the mapping builder. The working code looks like this:

static mapping = {
dateTimeProperty type: PersistentDateTimeTZ, {
column name: "date_time_property_timestamp"
column name: "date_time_property_zone"
}
}

The order of the columns corresponds to the order of the values returned by the sqlTypes() method of whatever UserType implementation you're using.