Spring MVC: Incorporating Java Map into Optgroup Options

In my Spring MVC project, I am currently passing a Map from Java to my webpage using the variable "userLocales" through request.setAttribute('userLocales', bluh bluh bluh).

I am looking for a way to extract the strings from this variable and use them to create a list of option elements within an optgroup select element. One approach I'm considering is converting this Map into a JavaScript object, and then adding the strings to newly generated option elements that will be inserted into the optgroup element.

The optgroup element has been pre-defined and is static. What I need are the options containing the respective strings.

Answer №1

It turns out, I stumbled upon the solution right after posting my question. How wonderful!

Source :

The attribute "optgroup" is used to sort items in a select list by defining an expression and inserting optgroup HTML tags accordingly. However, this functionality is not currently offered by Spring MVC tags. A workaround can be implemented as follows:

Map<String, ArrayList<String>>

In this map, the key is the group name and the arraylist contains the values belonging to that group. The JSP code can be structured like this:

<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>

Answer №2

Managing the Data

In this scenario, we are dealing with a collection named

Map<String, List<KeyValueBean>>
. This collection holds information like:

Group 1 -> 
             { ("Option 1.1 Label","OPTION_1_1_VAL"), ("Option 1.2 Label","OPTION_1_2_VAL"), ..}

@ModelAttribute("careerOptions")
Map<String, List<KeyValueBean>> getCareerOptions() {        
    HashMap<String, List<KeyValueBean>> result = new HashMap<String, List<KeyValueBean>>();
    result.put("Grp1", new ArrayList<KeyValueBean>());
    result.get("Grp1").add(new KeyValueBean("Option 1.1", "OPT_1_1"));
    result.get("Grp1").add(new KeyValueBean("Option 1.2", "OPT_1_2"));
    result.put("Grp2", new ArrayList<KeyValueBean>());
    result.get("Grp2").add(new KeyValueBean("Option 2.1", "OPT_2_1"));

    return result;
}       

Implementing in JSP

<form:select path="careerSelected" id="careerElement">
    <form:option label="" value="" />
    <c:forEach var="optionGroup" items="${careerOptions}">
       <optgroup label="${optionGroup.key}">
       <c:forEach var="option" items="${optionGroup.value}">
          <form:option label="${option.key}" value="${option.value}" />                             
       </c:forEach>                                                          
       </optgroup>
    </c:forEach>
</form:select>

Custom Java Bean

public class KeyValueBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private String key;
    private String value;

    public KeyValueBean(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }
    public void setKey(String key) {
        this.key = key;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

}

Dealing with Mixed Data Structures

Sometimes, the Select items have a mix of flat and grouped options as shown below:
A
B
C (subgroup)
  - C.1
  - C.2

In such cases, the Collection can be a Map where each entry is tied to an Object: (1) a String or (2) a HashMap. The distinction between them will be made in the JSP.

Controller for a Mix of Data Structures

@ModelAttribute("careerOptionsMixed")
Map<String, Object> getCareerOptionsMixed() {

    LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();

    result.put("Flat Option 1", "OPT_1_FLAT");
    result.put("Group Option 2", myHashMap); // Fill out your HashMap for Group (Key->Value) and add it here
    result.put("Flat Option 3", "OPT_3_FLAT");

    return result;
}           

JSP for Dealing with Mixed Data Structures

<form:select path="career" id="careerField">
   <form:option label="" value="" />
   <c:forEach var="optionOrOptionGroup" items="${careerOptionsMixed}">
      <%--  Must use iteration to find out if this is a Collection or not: https://stackoverflow.com/a/1490171/1005607 --%>
      <c:set var="collection" value="false" />
      <c:forEach var="potentialOptionGroup" items="${optionOrOptionGroup.value}" varStatus="potentialOptionGroupStatus">
         <c:if test="${potentialOptionGroupStatus.index > 0}">
            <c:set var="collection" value="true" />
         </c:if>
      </c:forEach>
      <c:choose>
         <c:when test="${collection eq true}">
            <%--  Now we know this is a LinkedHashMap --%>
            <optgroup label="${optionOrOptionGroup.key}">
               <c:forEach var="optionGroup" items="${optionOrOptionGroup.value}">
                  <form:option label="${optionGroup.key}" value="${optionGroup.value}" />
               </c:forEach>
            </optgroup>
         </c:when>
         <c:otherwise>
            <%--  Now we know this is a flat String --%>
            <form:option label="${optionOrOptionGroup.key}" value="${optionOrOptionGroup.value}" />
         </c:otherwise>
      </c:choose>
   </c:forEach>
</form:select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

button that smooth slides out using jquery

Here is the source code for a jQuery slideout: jQuery(function($) { $('#slideClick').toggle(function() { $(this).parent().animate({left:'0px'}, {queue:false, duration: 500}); }, function() { $(t ...

Resolved the time zone problem that was affecting the retrieval of data from the AWS Redshift database in Next

Currently utilizing Next.js for fetching data from AWS Redshift. When running a query from DataGrip, the results display as follows: orderMonth | repeatC | newC 2024-02-01 | 81 | 122 2024-01-01 | 3189 | 4097 However, upon retrieving the same query ...

What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model. The objective: Upon blur, the goal is to display an error if there is one; ho ...

How can I access a nested FormArray in Angular?

I have a situation where I am trying to access the second FormArray inside another FormArray. Here is an excerpt from my component: registrationForm = new FormGroup({ registrations: new FormArray([this.patchRegistrationValues()]) }); patchRegistrati ...

Convert millimeters to inches with a unique AngularJS filter that activates on click

I am currently working on a UI that requires users to enter dimensions for width and height. Within the UI, there are 2 buttons available - one for 'mm' and the other for 'inches'. When either of these buttons is pressed, the active cl ...

What is the best way to update a CSS href using window.open with JavaScript?

I am trying to dynamically change the CSS href by using window.open in JavaScript. <a class="cssButton" id="Launch" target="_blank" data-baseref="Example/index.html?" href="Example/index.html?" >Launch Example</a> I want to transform it into: ...

Troubleshooting issues with ember-data's belongsTo relationship

I am facing an issue with the model I have: Whenever I make a call to this.store.find('history'); A request is sent to http:://www.example.com/api/histories/ and I receive the following JSON response: { "tracks":[ { "id":83, ...

The anchor link is not aligning properly due to the fluctuating page width

Seeking help to resolve an issue I'm facing. Maybe someone out there has a solution? The layout consists of a content area on the left (default width=70%) and a menu area on the right (default width=30%). When scrolling down, the content area expand ...

Leveraging JavaScript to extract data from a JSON file upon clicking a button

Currently, I am working on a problem where the user enters values into a search box, clicks the search button, and then with the onClick event, the search terms are compared to values in a JSON file. I do not have knowledge of jQuery, so if there is a solu ...

Sticky positioning with varying column widths

How can I create HTML and CSS columns that stick together without manually specifying the "left:" parameter every time? The current example in the fiddle achieves what I want, but requires manual setting of the "left:" value. Is there a way to make this m ...

Is there a way to retrieve the selected value from a dropdown menu using vue.js?

I have a parent Vue component structured like this: <template> <form> <div class="row"> <div class="col-md-4"> <form-select id="color" name="color" :data="color">Color</form-select&g ...

Trigger ng-change event for each dropdown selection made in AngularJS

Currently, I have a dropdown menu that allows users to select a report for generation. When a user picks a report from the dropdown, it generates and downloads the report for mobile viewing. By utilizing ng-change, the system only detects when a user wants ...

Node.js error: Attempting to set property '' on an undefined object not allowed

I encountered an issue while attempting to update an array within a model. Even though the usagePlan is defined before the update, the error below keeps getting thrown. customer.usagePlan.toolUsage.tools.push(aNewToolObject); customer.updateAttribute(&apo ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

Why won't the props pass down to the child component?

I am facing an issue while trying to pass two values as props from a React component "App" to its child "Todo". The values being passed are "title" and "completed" from a json placeholder API. The JSON object is correct and has been verified. The problem ...

What is the best method for targeting the clicked element using its class name?

I have a scenario where there are multiple elements with the same class name, but I am only interested in changing the class of the element that is clicked. var icon = $('.opener i'); // Need to target the class of the clicked element Functi ...

Attempting to reduce the width of the dig when it reaches 400

I have a square element with a click event that increases its size by 50 pixels on each click. However, once it reaches a size of 400 pixels, the size decreases by 50 pixels with every click instead. Additionally, when the size of the square reaches 100 p ...

Access the original source code using jQuery

Is there a way to retrieve the raw HTML code (as seen in Chrome's source code window) using JQuery without having quotes converted to &quot or HTML symbols converted to text? I have tried using html() and text(), but neither method seemed to give ...

What is causing the table to not be displayed in this Javascript program when it is used in a

I am currently experimenting with incorporating an infinite loop before the prodNum and quantity prompts to consistently accept user input and display the output in a table. Although the program is functional when executed, it fails to showcase the table ...

Storing row details in Vue.js based on selected options from a dropdown menu

Displayed below is my code that generates a dynamic table. I am looking to save specific rows based on the selection made from a dropdown menu and then clicking on an update button. <b-field> <b-select name="contacted" id="" ...