Terence Ponce
Terence Ponce

Reputation: 9401

How do I combine multiple form inputs into a single object with SimpleFormController in Spring?

I have an object called Person that has the following properties:

int id;
Name name;
String address;
Date birthday;
String email;
String note;

The Name class has these properties:

String firstName;
String middleName;
String lastName;

In my form, I have these input fields:

<tr>
    <td>First Name:</td>
    <td><form:input path="firstName" /></td>
</tr>
<tr>
    <td>Middle Name:</td>
    <td><form:input path="middleName" /></td>
</tr>
<tr>
    <td>Last Name:</td>
    <td><form:input path="lastName" /></td>
</tr>

How will I be able to retrieve the value of the name input fields and turn it into a Name object before passing it to the Person object that will be created by the SimpleFormController? I'm pretty sure I need to use the initBinder() method, but I don't know how to start.

I'm using Spring 3.0, and yes, I know that SimpleFormController is deprecated already, but I still intend to use it.

Upvotes: 2

Views: 2615

Answers (1)

Ralph
Ralph

Reputation: 120881

You need to write:

<form:input path="name.firstName" />
...

in you jsp. And need to override the formBackingObject Method, so that it retuns an empty Person object with an reference to an emtpy name object

protected Object formBackingObject(HttpServletRequest request) {
   Person person = new Person();
   person.Name = new Name();
   return person;
}

Thats all, you do not need to write your own binding.

Upvotes: 5

Related Questions