0

让我们看一个简单的域类:

class Person { String aname }

让用户输入一个人的 gsp 表单很简单:

<g:form ...>
...
  someone:<input name="aname">
...
</g:form>

...然后回到控制器中,为了获取值,我可以写

def p = new Person(params)

现在,我想让用户以相同的形式输入两个人(比如说,两个父母)的数据。这个怎么写?我只是不能为两个输入字段提供相同的名称,但如果我不保留原始属性名称(“aname”),回到控制器中,我将不得不手动处理名称之间的绑定属性和表单输入名称:

<g:form ...>
...
  father:<input name="aname1">
  mother:<input name="aname2">
...
</g:form>

然后,在控制器中

def p1 = new Person(); p1.aname = params.aname1
def p2 = new Person(); p2.aname = params.aname2

即使表单中给出了多个相同类型的对象,是否有办法保持自动绑定功能?

4

3 回答 3

1

尝试使用这种方式:

<g:form ...>
...
  father:<input name="father.aname">
  mother:<input name="mother.aname">
...
</g:form>

和控制器:

def p1 = new Person(params.father); 
def p2 = new Person(params.mother); 
于 2013-05-06T14:51:33.440 回答
0

“名称”属性中的点表示法适用于<input>标签。

更进一步,“字段”插件还有一个解决方案:与其使用“名称”属性,不如使用“前缀”属性,如此处所述

例如:

<f:field bean="mother" property="forename" prefix="mother."/>
<f:field bean="mother" property="surname"  prefix="mother."/>
<f:field bean="father" property="forename" prefix="father."/>
<f:field bean="father" property="surname"  prefix="father."/>

<f:with>我们甚至可以在标签 的帮助下写得更好:

<f:with bean="mother"  prefix="mother.">
   <f:field property="forename"/>
   <f:field property="surname"/>
</f:with>
<f:with bean="father"  prefix="father.">
   <f:field property="forename"/>
   <f:field property="surname"/>
</f:with>
于 2013-05-07T12:11:57.137 回答
0

I suppose you are thinking of doing something like this:

<g:form ...>
...
  father:<input name="aname">
  mother:<input name="aname">
...
</g:form>

which would result as ?aname=Dad&aname=Mom

You can handle them in controller as below:

params.list('aname').each{eachName -> //Persist each `aname`}

Have a look at Handling Multi Parameters.

于 2013-05-06T14:17:05.213 回答