user4903
user4903

Reputation:

How do I set the selected value in a Spring MVC form:select from the controller?

In my controller:

@Controller
public class UserController {

    @RequestMapping(value="/admin/user/id/{id}/update", method=RequestMethod.GET)
    public ModelAndView updateUserHandler(@ModelAttribute("userForm") UserForm userForm, @PathVariable String id) {

        Map<String, Object> model = new HashMap<String, Object>();
        userForm.setCompanyName("The Selected Company");
        model.put("userForm", userForm);

        List<String> companyNames = new ArrayList<String>();
        companyNames.add("First Company Name");
        companyNames.add("The Selected Company");
        companyNames.add("Last Company Name");

        model.put("companyNames", companyNames);

        Map<String, Map<String, Object>> modelForView = new HashMap<String, Map<String, Object>>();
        modelForView.put("vars", model);

        return new ModelAndView("/admin/user/update", modelForView);
    }
}

The select form field in my view:

<form:form method="post" action="/admin/user/update.html" modelAttribute="userForm">
<form:select path="companyName" id="companyName" items="${vars.companyNames}" itemValue="id" itemLabel="companyName" />
</form:form>

It was my understanding that the form backing bean would be mapped based upon the modelAttribute attribute in the form. I'm obviously missing something here.

Upvotes: 14

Views: 96210

Answers (5)

Ayman Al-Absi
Ayman Al-Absi

Reputation: 2846

The easiest solution is to override the toString() method in the model class. In this case just change the class UserForm by overriding toString() like below:

@Override
public String toString() {
    return this.getCompanyName();
}

Spring then will automatically select the correct value in form:option

Upvotes: 8

NIrav Modi
NIrav Modi

Reputation: 6972

You can also try like this

<form:select id="selectCategoryId" path="categoryId"
      class="selectList adminInput admin-align-input" multiple="">
      <option value="0">-- Select --</option>
      <c:forEach items="${categories}" var="category">
            <option <c:if test="${category.key eq workflowDTO.categoryId}">selected="selected"</c:if>    value="${category.key}">${category.value} </option>
        </c:forEach>
</form:select>

Upvotes: 6

Dario Zamuner
Dario Zamuner

Reputation: 1041

I was struggling some time on the same issue. This is the select field I had

<form:select path="origin" items="${origins}" itemValue="idOrigin" itemLabel="name" />

Since I had a PropertyEditor in place for my entity I couldn't write something like

<form:select path="origin.idOrigin" items="${origins}" itemValue="idOrigin" itemLabel="name" />

that worked fine, but was not parsed by the PropertyEditor.

So, thinking about the Spring's need to determine equality between entities, I came out implementing equals and hashcode in my Origin entity using only the idOrigin property, and it worked!

Upvotes: 6

user4903
user4903

Reputation:

It appears the issue was not related to my setup. The problem was that the itemValue was set to the company id property, while the comparison was being done to the company name property on my form backing bean. So the two were not equal, and therefore, no item was set to selected.

The above code works just fine, and setting the value in the userForm for a particular property will set that value as selected in select form fields so long as the value of one of the items in the items collection is equal to the form value. I changed my form field to look like this, which pulls the companyName instead of the id.

<form:form method="post" action="/admin/user/update.html" modelAttribute="userForm">
<form:select path="companyName" id="companyName" items="${vars.companyNames}" itemValue="companyName" itemLabel="companyName" />
</form:form>

Upvotes: 11

Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

it is not so complicated. You need 2 beans: a form backing bean and a select model in your domain model.

Here is my model, a list of strings, for :

/* in controller: my select model is a list of strings. However, it can be more complicated, then you had to use PropertyEditors for String <-> Bean conversions */

    List<String> mySelectValues = new ArrayList<String>();
    mySelectValues.add("M");
    mySelectValues.add("F");
    modelMap.addAttribute("mySelectValues", mySelectValues);

Here is your form, basically :

<form:form command="user">
  <form:select path="gender">
     <form:options items="${mySelectValues}"></form:options>                                                                                                       
  </form:select>    
</form:form>

und here is my backing object:

public class User {
    private String gender;
    /* accessors */
}

Spring framework selects automaticaly using value of "gender" field.

Upvotes: 3

Related Questions