D
D
dima_eam2014-03-20 11:52:57
Spring
dima_eam, 2014-03-20 11:52:57

Spring MVC - how to save data from checkboxes to a collection?

Hey! The project has a class Company, which has a field of the Set type. It is necessary to fill this field with values ​​from the checkboxes that the user selects on the page.
JSP code:

<td><form:checkboxes path="activities" items="${activities}" itemValue="id" itemLabel="name"/><br/>
<form:errors path="activities"/></td>

The controller has a method annotated with @InitBinder to convert strings into collection elements:
@InitBinder
    protected void initBinder(WebDataBinder binder) throws Exception {
        binder.registerCustomEditor(Set.class, "activities", new CustomCollectionEditor(Set.class) {
            @Override
            protected Object convertElement(Object element) {
                if(element instanceof Activity){
                    return element;
                }
                if (element instanceof String) {
                    Activity act = allAct.get(Integer.valueOf(element.toString()));
                    return act;
                }
                return null;
            }
        });
    }

If you select only one checkbox, then the Company object is created, if more than one, an error message is displayed:
"Failed to convert property value of type java.lang.String[] to required type java.util.Set for property activities; nested exception is java.lang.NumberFormatException: For input string: "1,2""
Although the initBinder method is called and normally creates Activity objects.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Kulakov, 2014-03-20
@carbon88

well so to you wrote that the format of a line is not correct. as I understand it, the numbers of checkboxes separated by commas are stored in activities. then in line
a string like "1,2" (which is just contained in the error message) is converted to an integer and, of course, nothing happens.
in theory, you need to check whether there is one element or a sequence in activities and, in the case of a sequence, divide it into specific elements and feed them to the registerCustomEditor method one by one

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question