How do I initialise a Date field in a Grails domain object to act as a timestamp?
Asked Answered
M

1

5

I have a domain class which has two dates in it and I want one of them populated with the current time when a record is created for the object, like a create timestamp...

class Contact {
    Date initiatedDate
    Date acceptedDate
}

Is it sufficient just to new a Date object on one of them and make the other nullable until such a time as I need to fill it, sort of like this...

class Contact {

    static constraints = 
    {
        acceptedDate(nullable:true)
    }

    Date initiatedDate = new Date()
    Date acceptedDate
}

I'm experimenting, but I would like to know whether this is the right way to go about it or whether there is something more Grailsy or GORMy I should do in, say, an init function or by tweaking the domain object definition to have one by default, like it does an id and version.

Thanks

Mislike answered 27/1, 2010 at 13:41 Comment(0)
S
9

What you've written should work but you can use the GORM auto-timestamping feature by simply adding a field:

class Contact {
    Date dateCreated
}

If you want to keep your own names for the fields the same grails docs also show you how to use GORM events to set fields on save or update.

HTH

Sabec answered 27/1, 2010 at 13:54 Comment(1)
that's exactly the sort of GORMy thing I was looking for, thanksMislike

© 2022 - 2024 — McMap. All rights reserved.