Deleting an item from an indexed property - JavaBeans question

822 views Asked by At

I'm working with indexed properties (using struts and java/jsp). We have a dynamic table that can add/delete rows/items in the table. The adding of rows works as intended - I see the new rows in the form in the action class. The deleted rows do not get set (obviously), but they are also not removed from the list. I have implemented a void setItem(List), void setItem(index), Item getItem(index) and List getItem() methods. I can't find much information regarding the behavior of indexed properties. Is there a reset method that I need to implement, or are indexed properties supposed to take care of setting a new list? From what I can tell, only the items still in the list are set, and they're set using the void setItem(Item) method.

1

There are 1 answers

0
Thierry Roy On
  • Make sure your form is request scoped, not session scoped
  • Use a LazyList.

For example:

private List<PropertyContact> contactsList = LazyList.decorate(new ArrayList<PropertyContact>(), PropertyContact.PROPERTY_CONTACT_FACTORY);

public static final Factory PROPERTY_CONTACT_FACTORY = new Factory() {
        @Override
        public Object create() {
            return new PropertyContact();
        }
    };

Then you can display/edit the list in your JSP like so:

<c:forEach items="${profileForm.contactsList}" var="contact" varStatus="contactSta">
    <html:hidden styleClass="contact-id" property="contactsList[${contactSta.index}].id"/>
</c:forEach>

If you want to add elements to the list, make sure you set an index superior than the maximum one. For example if my list contains 3 elements, the new one (the fourth) will look like this: (remember that list are zero-index based)

<input style="hidden" styleClass="contact-id" property="contactsList[3].id"/>

When the form is submitted, any list element deleted will set a null at the specific index. For example, let's say the user deletes the 2nd elements, I will see on the server:

contactsList.get(1) == null;//remember that list are zero-index based