Fred B.
Fred B.

Reputation: 85

how to get several same object values in a Grails form

let's take a simpe domain class:

class Person { String aname }

A gsp form to let the user input a person is easy:

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

... and back in the controller, to get the values, I can just write

def p = new Person(params)

Now, I'd like to let the user input the data for two persons (let's say, two parents) in the same form. How to write this ? I just can't give the same name for the two input fields, but if I don't keep the original property name ("aname"), back in the controller I will have to handle by hand the bindings between the name of the property, and the form input names:

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

then, in controller

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

Is there a way to keep the automatic binding facility even if there is several objects of same types given in a form ?

Upvotes: 0

Views: 1225

Answers (3)

Fred B.
Fred B.

Reputation: 85

the dot notation in the "name" attribute works well for the <input> tag.

To go further, there is also a solution for the "fields" plugin: rather than using the "name" attribute, one should use the "prefix" one, as described here.

For example:

<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."/>

we can even write it better, with help of <f:with> tag:

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

Upvotes: 0

Mr. Cat
Mr. Cat

Reputation: 3552

Try to use this way:

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

And controller:

def p1 = new Person(params.father); 
def p2 = new Person(params.mother); 

Upvotes: 1

dmahapatro
dmahapatro

Reputation: 50245

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.

Upvotes: 0

Related Questions