问题
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.
回答1:
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.
回答2:
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 )
回答3:
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 :)
回答4:
You still need to know the format though
def newObject = new SomeClassName()
newObject.foobar = Date.parse('yyyy-MM-dd', params.foobar)
来源:https://stackoverflow.com/questions/534330/reading-the-gdatepicker-value-in-grails-without-using-the-new-objectparams