PDA

View Full Version : Struts, Forms, and Dynamic Lists... and a headache


pooter8d
07-11-2007, 05:27 PM
I'm having a problem figuring out the best approach to a struts problem that includes an html:form and creating a list of html:text boxes.

Background: a basket (cart) page on an ecommerce site that will list all the items (in a list of item bean) with a single text box to edit the quantity of a particular product the user wishes to buy or 0 for removing the product from the list.

I am passing the basket list as a session attribute but when i have a loop for (Item i : ItemList) that creates a html:text, the property is always the same so for n amount of items only the top most item can be changed as of current. I have tried to include a seperate button in that loop so along with each text box and description is an individual button and still the same result.

Is there a way that struts knows to fill the action form bean with all the different items in an array. I have thought of useing just 1 submit button with all the fields, but still when struts passes along the properties doesnt it need a corresponding java bean already statically created?

Maybe i'm going about it all wrong? I have even tried to include a hidden input as getIndexOf(Item i) from the list.

So i'm stuck.. the easy way out would be to create a new jsp page that will be called on a click of an item from the list and then individually edit, but that would be annoying for the client.

Many thanks

cash1981
07-12-2007, 05:53 PM
Could you please post the code snip so I can have a look?

pooter8d
07-13-2007, 12:41 PM
In my jsp:



<%

List<OrderItem> basketList = (List) session.getAttribute("basket");

%>

...

if (basketList.size() == 0) {

out.println("<ul><li>No items in your basket</li></ul>");

}

else {

%>

<html:form action="EditBasket.do">

...

<%

for (OrderItem ordItem : basketList) {

out.print("<TR><TD align='center'>"); %>

<html:text

property="<%="item" + String.valueOf(basketList.indexOf(ordItem))%>"

value="<%=String.valueOf(ordItem.getQuantity())%>"

size="3"

maxlength="3"/>



<% out.print("...PRINT TABLE OF VALUES FOR EACH ORDERITEM");

...

</html:form>





In my action...



try {

List items = editBasketForm.getItems();



for (Object o : items) {

OrderItem item = (OrderItem) o;

}



// Get form data

String qty = editBasketForm.getQuantity();

// String itemnumber = editBasketForm.getItemNumber();



// Get basket

HttpSession session = request.getSession();

List<OrderItem> basketList = (List) session.getAttribute("basket");



// Get item in basket to update

OrderItem item = basketList.get(Integer.parseInt(itemnumber));



// Set new quantity

item.setQuantity(Integer.parseInt(qty));





In my form bean ...





private List items = new ArrayList();

private String quantity = null;



... Getter's + setters.