DiscDev
DiscDev

Reputation: 39052

Using SpringMVC form:select to bind comma separated values to multiple dropdown lists

I am designing a jsp page, where users can select values from a dropdown like:

Row1: Select "dropdown"

Row2: Select "dropdown"

Row3: Select "dropdown1" "dropdown2"

where:

dropdown values are {1,2,3,4,5,6,7}

Users can select the values from the above rows and save the form. The next time the user views the page and the saved values are retrieved from the database, I want to display them in the dropdowns. For that I am using Spring MVC form:select automatic binding

<form:select id="${id}" path="Mappings[${index}].userSetting">
            <c:forEach var="item" items="${dropdownValues}">
                <form:option value="${item.value}"><spring:eval expression="item" /></form:option>
            </c:forEach>
</form:select>

The code works fine for Row1 and Row2 which only have 1 dropdown to bind to. But in case of Row3, the Mappings[${index}].userSetting returns values like "2,3" (instead of a single value), which are from the dropdownValues list but comma delimited. In this case, for obvious reasons Spring MVC form:select fails to select values from the dropdown because "2,3" cannot be found in either of dropdowns. What I am trying to do is to split the values so that from the "2,3", the value "2" and "3" are selected such that Row3 looks like:

Before: Select "dropdown1" "dropdown2" After: Select "2" "3"

Does anyone have a suggestion for how to accomplish this?

Upvotes: 1

Views: 2778

Answers (1)

Jean-Philippe Bond
Jean-Philippe Bond

Reputation: 10649

Have you thought about the fn:split() function.

Here an example of what you could do :

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<c:set var="row3Value" value="${fn:split(model.getMappings()[${index}].userSetting, ',')}" />

<form:select id="${id}" path="Mappings[${index}].userSetting">
    <c:forEach var="item" items="${dropdownValues}">
        <c:choose>
            <c:when test="${row3Value[0] eq ${item.value}}">
                <form:option selected="true" value="${item.value}"><spring:eval expression="item" /></form:option>
            </c:when>

            <c:otherwise>
                <form:option value="${item.value}"><spring:eval expression="item" /></form:option>
            </c:otherwise
        </c:choose> 
    </c:forEach>
</form:select>

Upvotes: 2

Related Questions