views:

2535

answers:

4

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.

A: 

You still need to know the format though

def newObject = new SomeClassName()
newObject.foobar = Date.parse('yyyy-MM-dd', params.foobar)
tcurdt
The value of params.foobar is the string "struct", so your solution does not work unfortunately.
knorv
Ups - thought g:datePicker sends it through as one string.
tcurdt
+4  A: 

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.

mycro.be
A: 

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 :)

chanwit
+1  A: 

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 )

knorv