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.
Would become:Code:dateOfBirth_day 13 dateOfBirth_month 2 dateOfBirth_year 2005
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.Code:dateOfBirth day=13\nmonth=2\nyear=2005
I'm a lot happier with this approach than other ones I've used anyway.


Reply With Quote