Spring form:select multiple selected value?

杀马特。学长 韩版系。学妹 提交于 2019-12-06 09:33:47

Why are you writing your own? Spring should be able to do that for you. Instead of a <c:forEach /> replace that whole block with a <form options .. /> tags. Spring will then be able to do the selection itself (you might need a Converter or PropertyEditor for that).

<form:select multiple="true" path="roles" items="${roles}" itemLabel="nombre" itemValue="id" />

Something along these lines...

Links:

  1. Form Options documentation
  2. Form Select documentation
  3. Reference Guide

If you use this:

<form:select multiple="true" path="roles" items="${roles}" itemLabel="nombre" itemValue="id" />

you need to override toString() method of Usuario_Rol, in the right way for your class, to ensure that Spring pre-selects the initial values for you.

If I understand the question correctly, what you want is your Spring tag to generate HTML like this one:

    <select id="roles" name="roles multiple="multiple">
       <option value="1">Administrador</option>
       <option value="2">Usuario avanzado</option>
       <option value="3" selected="selected">Usuario </option>
       <option value="4" selected="selected">Invitado</option>
    </select>

As you can see, two values are selected ("Usuario" and "Invitado").

The "roles" model attribute that "path" refers to in your Spring tag has be an array instead of a single value. It's as easy as that. Please be aware that I set the array by hand in my controller. I am not familiar with the implications on the ORM side of your code.

I think you want to expect output like this:

<select id="roles" name="roles" multiple="multiple">
 <option value="1">Administrador</option>
 <option value="2" selected="selected">Usuario avanzado</option>
 <option value="3" selected="selected">Usuario </option>
</select>

In model class you can create method for "roles" which should return array. Add your business complexity in that method.

public Integer[] getRoles(){
    Integer[] selectedRoles = {2,3};
    return selectedRoles;
}

In JSP:

<form:select multiple="true" path="roles">
    <form:options items="${...}" itemValue="..." itemLabel="..."/>
</form>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!