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)?
You should use Grails’ data-binding support by declaring a command object like this
If you construct your form so that the request parameters are named like this:
The data will be automatically bound to the
personCommandargument of this controller actionIf you call
personCommand.validate()it might in turn callvalidate()on eachPersoninpeople(I’m not sure). If it doesn’t you can do this yourself by callingAt this point you’ll know whether all
Personinstances are valid. If they are not, you should pass thePersonCommandback 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-allfor a domain class and look at the GSP code it generates.