How to associate a Checkbox to a List of Objects in Spring MVC

Asked

Viewed 352 times

1

Next up, folks, I’m having a little bit of a doubt about the manipulation of a checkbox list. I have a list of objects that are the Courses, and I would like that list to be linked to a 'List' of another class as follows:

It is in the JSP

<ul><form:checkboxes element="li" path="aluno.cursos" itemValue="id" itemLabel="nome" items="${cursoList}"></form:checkboxes></ul>

Class to which it must be bound

@Document(collection = "alunos")
public class Aluno {
...
private List<Curso> cursos;
...
public List<Curso> getCursos() {
    return cursos;
}

public void setCursos(List<Curso> cursos) {
    this.cursos = cursos;
}
...

In my controller the function is as follows:

public ModelAndView registered(@ModelAttribute("aluno") Aluno aluno, BindingResult result, HttpServletRequest request) {
    System.out.println("Registrando: " + aluno.toString());
    ...
}

At this point, I see that the list of courses of the student class should be set, however, lies NULL What is the right way for me to link this list of Checkboxes to my list of the Student class?

1 answer

1

Your code seems correct, so the problem must be elsewhere.

Probably the problem is that the methods still need to be implemented equals() and hashCode in class Curso.

Note that when HTML is rendered on the screen, checkboxes "lose" the information of the original object, possessing only the id as value. When the form is resubmitted to the server, Spring receives the ids selected and need to find the corresponding objects to then add to the final list specified in the attribute path.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.