PDA

View Full Version : Approach for handling dynamic list objects for data binding



msqr
Aug 16th, 2004, 06:03 PM
I've been working through various ways of solving an issue I have with form submissions dealing with dynamic list data binding. Easiest to explain with an example. Let's say I have some domain objects like this (assuming classes have appropriate getters/setters, but nothing else):



public class Recipe {
private String name;
private List ingredients;
}
public class RecipeIngredient {
private int quantity;
private Ingredient ingredient;
private Unit unit;
}
public class Ingredient {
private String name;
}
public class Unit {
private String name;
}


Here is a Recipe, which is meant to have a list of RecipeIngredient objects, each of those has an Ingredient object. Then I have an HTML form, which uses DHTML to allow the user to associate as many recipe ingredients they wish with the recipe, and then submit, resulting in request parameters such as:


recipe.name=Chocolate Chip Cookies
recipe.ingredients[0].quantity=1
recipe.ingredients[0].unit.name=Bag
recipe.ingredients[0].ingredient.name=Chocolate chips
recipe.ingredients[1].quantity=2.5
recipe.ingredients[1].unit.name=Cups
recipe.ingredients[1].ingredient.name=Flour


And so on. The problem is that Spring won't automatically create new RecipeIngredient, Ingredient, or Unit objects on demand to satisfy the form submission. In the case of RecipeIngredients, Spring wouldn't even know that the List property 'ingredients' should contain RecipeIngredient objects. Thus my question is, what is the best way to model a DataBinder to dynamically instantiate RecipeIngredient objects (and subsequently Ingredient and Unit objects).

My current approach involves extending the ServletRequestDataBinder class and overriding the bind(ServletRequest request) method, in which I inspect the request parameters, looking for possible "missing" RecipeIngredient objects and create new instances and populate those new instances in the Recipe object, all before returning control back to ServletRequestDataBinder's bind() method to complete the data binding. This approach is working for me, but I'm wondering if this is a good approach.

Before anyone suggests I alter the domain objects to, say, initialize the RecipeIngredient list and/or Ingredient and Unit objects of those objects in the Recipe constructor or whatnot... this is not an option for me and one should consider the domain objects "un-modifiable". It happens that they are generated classes in my situation, and I don't have the option to alter them.

Much appreciation in advance for any ideas / suggestions![/list]

David Malone
Jun 24th, 2007, 10:58 AM
I have also been searching for a solution for this problem. I found what appears to be a working example:

http://mattfleming.com/node/134