不使用“new Object(params)”方法读取 Grails 中的 g:datePicker 值
假设我有一个名为“foobar”的日期选择器:
<g:datePicker name="foobar" value="${new Date()}" precision="day" />
如何读取此日期选择器的提交值?
一种可行但有一些不需要的副作用的方法如下:
def newObject = new SomeClassName(params)
println "value=" + newObject.foobar
这种方法将所有提交的字段读取到 newObject 中,这是我想避免的。 我只对“foobar”字段的值感兴趣。
我最初认为可以这样做的方法是:
def newObject = new SomeClassName()
newObject.foobar = params["foobar"]
但是 Grails 似乎不会自动将 foobar 字段转换为 Date() 对象。
更新:其他信息可以在 Grails JIRA 中找到。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用命令对象习惯用法。 在您的示例中,我将假设您的表单调用操作
handleDate
。 控制器内部:这是
FoobarDateCommand
。 请注意如何将字段命名为与视图中相同的名称:命令对象是封装每个表单的所有验证任务的便捷方法,使控制器保持美观和小巧。
Use the command object idiom. In the case of your example, I will assume that your form calls the action
handleDate
. Inside the controller:Here's
FoobarDateCommand
. Notice how you name the field the same as in the view:Command objects are a handy way to encapsulate all validation tasks for each of your forms, keeping your controllers nice and small.
在 Grails 1.2 中,读取 g:datePicker 值变得更加容易(请参阅发行说明) :
Reading the g:datePicker value became a lot easier in Grails 1.2 (see release notes):
当参数说是“结构”时,这意味着有许多参数来表示其值。 在你的情况下,有:
只需将它们取出并做你想做的任何事情:)
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:
Just fetch them out and do whatever you want :)
不过你仍然需要知道格式
You still need to know the format though