0

I have a Person class with two properties: name and address. I want to build a GSP page which allows for 10 users to be created at one time. This is how I'm implementing it and was wondering if there is a better way:

First, make 20 text boxes in the GSP page - 10 with someperson.name and 10 with someperson.address field names (make these in a loop or code them all individually, doesn't matter).

Second, process the submitted data in the controller. The someperson object has the submitted data, but in a not-so-nice structure ([name: ['Bob', 'John'], address: ['Address 1', 'Address 2']]), so I call transpose() on this to be able to access name, address pairs.

Then, build a list of Person objects using the pairs obtained from the previous step and validate/save them.

Finally, if validation fails (name cannot be null) then do something... don't know what yet! I'm thinking of passing the collection of Person objects to the GSP where they are iterated using a loop and if hasErrors then show them... Don't know how to highlight the fields which failed validation...

So, is there a better way (I should probably ask WHAT IS the better way)?

zoran119
  • 10,657
  • 12
  • 46
  • 88

1 Answers1

1

You should use Grails' data-binding support by declaring a command object like this

class PersonCommand {

  List<Person> people = []
}

If you construct your form so that the request parameters are named like this:

person[0].name=bob
person[0].address=england
person[1].name=john
person[1].address=ireland

The data will be automatically bound to the personCommand argument of this controller action

class MyController {

  def savePeople = {PersonCommand personCommand->

  }
}

If you call personCommand.validate() it might in turn call validate() on each Person in people (I'm not sure). If it doesn't you can do this yourself by calling

boolean allPersonsValid = personCommand.people.every {it.validate()}

At this point you'll know whether all Person instances are valid. If they are not, you should pass the PersonCommand back to the GSP and you can use the Grails tags:

  • <g:eachError>
  • <g:hasErrors>
  • <g:renderErrors>

to highlight the fields in errors. If you're not exactly sure how to use these tags to do the highlight, I suggest you run grails generate-all for a domain class and look at the GSP code it generates.

Dónal
  • 185,044
  • 174
  • 569
  • 824
  • How does Grails know to bind `person` from the request to the command object? I'd expect the parameters to be required as `people[0].name=bob` – zoran119 Dec 01 '11 at 02:29
  • I keep getting `Error occurred creating command object.` and `Exception Message: Index: 1, Size: 0` with this code http://pastie.org/2951846 Any idea why? – zoran119 Dec 01 '11 at 22:06
  • have a look at the answers to this question http://stackoverflow.com/questions/5677623/grails-command-object-data-binding – Dónal Dec 02 '11 at 13:56