Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 837
Simon Avatar asked Jan 27 '10 13:01

Simon


1 Answers

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

like image 181
Dave Bower Avatar answered Oct 05 '22 06:10

Dave Bower