views:

278

answers:

0

How would explicit hidden input elements be bound a model attribute?

I'm not using <spring:bind> or <form:hidden>. I have a Form bean that has an object with a child collection. A user adds to that collection on the fly...

public class Parent {
    List<Child> children = new ArrayList<Child>();
}

public class Child {
    String name;
}

public class Form {
    Parent parent;
}

public String onSubmit(@ModelAttribute("form") Form form, ...) {
    // form.getParent().getChildren() is always empty
}

In my JSP I have:

<input type="hidden" name="parent.children[index].name" value="" />

The value is populated by Javascript eventually, but when I debug the form post, the @ModelAttribute never has a value for any of the children and the HttpServletRequest doesn't have any of the child parameters.

Is there a way to do this manually?

I'm also adding on the fly:

function add_on_fly(stuff) {
    var index = $('#myTable tr').length - 1;
    $('#myTable tr:last').after('<input type="hidden" name="parent.children['+index+'].name" value="'+stuff+'" />');
}

Any ideas?

EDIT: got this working...

Hopefully this will help someone else in the future. It's not enough to instantiate an empty array of child elements because:

parent.children[index]

becomes

parent.getChildren().get(index)

which returns null because it isn't created yet. I got to work via:

http://mattfleming.com/node/134

Using the commons-collections LazyList:

List<Child> children = LazyList.decorate(new ArrayList<Child>(), new Factory() {
    public Object create() {
        return new Child();
    }
});

So each add() and get() calls have a Factory generated object to set properties via reflections on the Spring backend. I tried overriding add and get to no avail.

Also, there's no need to include parent reference, i.e. this works:

children[index].name