Binding composite properties with DataBinder
I have frequently come across the problem of binding multiple form fields to a single property. The whole binding infrastructure is geared to mapping a single input field to a single property, which is fine for most cases. It really falls over for things like dates - it seems a lot of people are using plain text input fields and demanding dates in a particular format. A far more common approach is to use multiple select boxes - one for day, month and year. The problem then is how to combine those into a single property value.
This is a problem I've solved, and seen solved a number of times, and never been entirely happy with the result. I've recently come up with a mechanism that works quite well for me, and I'll post the code up if anyone's interested.
The basic sequence is as follows:
Submit a form with a composite property on it. Form fields should follow the convention propertyName_partName. Eg, dateOfBirth might have three fields, dateOfBirth_day, dateOfBirth_month and dateOfBirth_year.
The controller uses a subclass of ServletRequestDataBinder that manipulates the array of PropertyValues to convert multiple parts of a composite property into a single property, the value of which gives all parts and values in the standard Properties format. Eg.
I have an AbstractCompositePropertyEditor that converts the string into a Properties object. Then, you just have to extend it to convert the values in the Properties instance into whatever is expected by the underlying property, and register that PropertyEditor against your field.
I'm a lot happier with this approach than other ones I've used anyway.
simple approach using javacript
A less generic but simple approach is to use javacript. On form submit, combine the parts into a hidden field. To Spring, that would look as if you were using a plain text input field. IMO, this qualifies as presentation logic and can therefore be handled at the view level.