javascriptjavaspring-mvcoptgroup

How to put Java Map into Optgroup Options Using Spring MVC?


I am using Spring MVC.

I currently have a Map being passed from Java to my page in a variable called "userLocales" via request.setAttribute('userLocales', bluh bluh bluh)

I need to somehow get the strings in that variable to build a list of option elements in an optgroup select element. My initial thought would be to somehow turn this Map into a Javascript object somehow, and then add the strings to newly created option elements to be placed in the optgroup element.

The optgroup element is static and already created. I just need the options with the string in them.


Solution

  • And I think I found the answer right after I posted this question. Wonderful

    Source : http://www.imrantariq.com/blog/option-group-capability-for-spring-mvc-form-taglib/

    The “optgroup” attribute when set would first do a sort by whatever “expression” is defined in “optgroup”, and then would track the progression of iteration and insert the “optgroup” html start tag, and end tags where appropriate in the select list using the expression in “optgroup” as the label.

    Unfortunately, currently spring mvc is not offering such functionality through its tags. This can be achieved through a nice logic given below. You need to send a hashMap from controller.

    Map<String, ArrayList<String>>
    

    In this map, string is key i.e. group name and arraylist is the number of values that lies in this group. Jsp code can be written in this way.

    <form:select multiple="single" path="itemType" id="itemType">
        <form:option value="0" label="Select" />
        <c:forEach var="itemGroup" items="${itemTypeList}" varStatus="itemGroupIndex">
           <optgroup label="${itemGroup.key}">
               <form:options items="${itemGroup.value}"/>        
           </optgroup>
        </c:forEach>        
    </form:select>