Thursday, April 14, 2011

Damn easy Spring MVC complex object binding within collection

During the development of our web application using Spring MVC, we wanted to allow the modification of some data such as an Actor which has an id and a name. We didn't want to show the id, only the name.

The problem is how to bind back the modified name ? We tried using PropertyEditor but this is handy to transform some data to String and back. I searched the web but at last, I understood how to do that very easily.


<ul>
    <c:forEach items="${form.actors}" var="actor" varStatus="status">
        <li>
            <form:hidden path="actors[${status.index}].id" />
            <form:input path="actors[${status.index}].name" />
        </li>
    </c:forEach>
</ul>

Et voilĂ  !

The id is bound back to the Actor as the modified name.

Note : the actors collection must be a List or an Array.

2 comments:

  1. Those damn simple 8 lines are exactly what I've been looking for the whole afternoon !

    You saved my day :)

    ReplyDelete
    Replies
    1. Thanks. It is exactly why I wanted to post this kind of thing.

      FYI, you should consider using an secure token in your form to protect it as someone can change the id of the entity. This in known as CSRF.

      Delete