Wednesday, March 30, 2011

Reading the g:datePicker-value in Grails without using the "new Object(params)"-method

Let's say I have a datePicker called "foobar":

<g:datePicker name="foobar" value="${new Date()}" precision="day" />

How do I read the submitted value of this date-picker?

One way which works but has some unwanted side-effects is the following:

def newObject = new SomeClassName(params)
println "value=" + newObject.foobar

This way of doing it reads all submitted fields into newObject which is something I want to avoid. I'm only interested in the value of the "foobar" field.

The way I originally assumed this could be done was:

def newObject = new SomeClassName()
newObject.foobar = params["foobar"]

But Grails does not seem to automatically do the translation of the foobar field into a Date() object.

Updated: Additional information can be found in the Grails JIRA.

From stackoverflow
  • You still need to know the format though

    def newObject = new SomeClassName()
    newObject.foobar = Date.parse('yyyy-MM-dd', params.foobar)
    
    knorv : The value of params.foobar is the string "struct", so your solution does not work unfortunately.
    tcurdt : Ups - thought g:datePicker sends it through as one string.
  • Use the command object idiom. In the case of your example, I will assume that your form calls the action handleDate. Inside the controller:

    
    def handleDate = { FoobarDateCommand dateCommand ->
        def theNextDay = dateCommand.foobar + 1
    }
    

    Here's FoobarDateCommand. Notice how you name the field the same as in the view:

    
    class FoobarDateCommand { 
        Date foobar 
    }
    

    Command objects are a handy way to encapsulate all validation tasks for each of your forms, keeping your controllers nice and small.

  • When a param says to be a "struct", this means there are a number of params to represent its value. In your case, there are:

    • params["foobar_year" storing year
    • params["foobar_month"] storing month
    • params["foobar_day"] storing day

    Just fetch them out and do whatever you want :)

  • Reading the g:datePicker value became a lot easier in Grails 1.2 (see release notes):

    Better Date parsing

    If you submit a date from a tag, obtaining the Date object is now as simple as looking it up from the params object by name (eg. params.foo )

0 comments:

Post a Comment