Populate Collection from Struts2 Form Submission
Asked Answered
C

1

5

I'm trying to populate a List of beans from a form:

public class Foo {
   public String attr1;
   public String attr2;
}

public class Bar {
   public List<Foo> foos;
}

public class StrutsAction extends Action {
   public Bar bar;
}

So in my Struts2 form, what's the best way to populate Foo? Intuitively, I want to do:

<input type="hidden" name="bar.foos.attr1" />

but that isn't working and would cause collisions. I'm sure the answer is very simple and I'm overlooking it.

Coagulase answered 10/6, 2009 at 14:18 Comment(0)
K
12

If I understand it correctly, you just want different name for each hidden field?

<s:iterator value="bars" status="key">
    <s:hidden name="bar.foos[%{#key.index}].attr1" value="attr1" />
    <s:hidden name="bar.foos[%{#key.index}].attr2" value="attr2" />
</s:iterator>

which should give you the equivalent of

<input type="hidden" name="bar.foos[0].attr1" value="some value" />
<input type="hidden" name="bar.foos[0].attr2" value="some other value" />
<input type="hidden" name="bar.foos[1].attr1" value="some value" />
<input type="hidden" name="bar.foos[1].attr2" value="some other value" />

If you have proper getter/setter, it should set all the values when the form is being submitted.

Karrah answered 10/6, 2009 at 18:51 Comment(2)
You are correct sir. I suppose I simply didn't know the proper syntax (i.e. the [0]).Coagulase
Thank you...! it helped me too...(even after 2 years :-P)Protection

© 2022 - 2024 — McMap. All rights reserved.