This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

Handle Complex Forms

Aug 26th, 2009, 01:27 PM

Hi Guys,

In the SimpleFormController, we can use the command object to get the information from the form.
This command object is usually a POJO bean for a entity. The only problem I see is we can get (or pass)
maximum one Command object and I don't know how to handle complex form fields ()

Yes, there is only one command object, but it can certainly have nested objects, so that you can bind a text box to, for example, person.contactInfo.homeAddress.streetAddress or some such.

Similarly, if your command object contains a collection (e.g. a List) you can bind a text box to person.universityDegrees[0].degreeType and then bind another text box to person.universityDegrees[1].degreeType.

I hope these fictional examples are helpful -- if you give an example of what would be in your form, we should be able to give you advice about how to bind that form to a single command object.

Comment

Well, you can't, really. The nature of a command or "form-backing object" is that it's just that -- a single object that contains the data from a form.

So, your options include:

1) change your form or set of models -- if one form is putting stuff in several unrelated model objects, perhaps your form is trying to do too much (or your models are splitting functionality across too many objects).

or

2) create a "container" object to be your command object, that simply contains instances of the various objects that the form will bind to.

or

3) some developers prefer to create separate command objects that are just used for a given form, and aren't necessarily the same as the model objects that your business logic act on. You use the command object just to set or retrieve the form data, and then copy that data into the appropriate domain objects. This also has the advantage that you can make your command objects very flat (no nested objects) even if the domain model is not flat (which makes your JSP code simpler).

or

4) do some of it manually -- let's say almost all of the fields bind to a single object but you have one extra field that should go to another object. You can always just not use Spring binding for that one field, but instead just use request.getParameter("name_of_field") and put the data into the object manually within your controller. It's messy but an option.