Smith
Smith

Reputation: 1469

How to get selected item id and value of form:select in a Spring MVC

I'm new to Spring and I would like to get id and value of selected item of a dropdown. Here is a simple example

class MaritalStatus{
    private int id;
    private String status;
}

class regForm{
    private MaritalStatus maritalStatus;
    ...
}

//Simple Controller to fill the list

@RequestMapping(value = "/save")
public String init(Model model){
    List<MaritalStatus> maritalList = new ArrayList<MaritalStatus>();
    maritalStatus.setId(1)
    maritalStatus.setStatus("Married")
    maritalList.add(maritalStatus);// add all status to the list....

    model.addAttribute("maritalList",maritalList);
    ...
}

jsp page

<form:form commandName="regForm" action="save">
    <form:select path="maritalStatus.id">
        <form:options items="${maritalList}" itemValue="id" itemLabel="status" />
    </form:select>
</form:form>

This is where I want to get selected item id and value (1 and Married)

@RequestMapping(value = "/save")
public String save(Model model,@ModelAttribute("regForm") RegForm regForm){
    // here I want to get selected item Id and Status(Label)
    //regFrom.getMaritalStatus().getId() and regFrom.getMaritalStatus().getStatus()
}

Upvotes: 0

Views: 8917

Answers (2)

Prasad
Prasad

Reputation: 3795

You can get status by one hidden variable in jsp and a javascript function.

    function changeStatus() {
    var statusSelected = document.getElementById("maritalStatus");
    var option = cookerModeIdSelected.options[statusSelected.selectedIndex];
    var selectedValue = option.getAttribute("data-status");
    document.getElementById("regForm").submit();        
}

<form:form commandName="regForm" action="save">
<form:hidden id="maritalStatusValue" path="maritalStatusValue"/>

<form:select path="maritalStatus.id" id="maritalStatus">
    <form:options items="${maritalList}" itemValue="id" itemLabel="status" data-status="${status}"/>
</form:select>
</form:form>

Upvotes: 0

Łukasz Dumiszewski
Łukasz Dumiszewski

Reputation: 3038

You can achieve it at least in 2 ways:

  1. Send only the id of the selected MaritalStatus (you actually do it in your jsp), bind it directly to regForm.maritalStatusId and then (when you need it) get the MaritalStatus from the maritalList by the selected id (you have to keep the maritalList or create it somewhere, you do it anyway)

  2. Bind your select directly to regForm.maritalStatus <form:select path="maritalStatus"> and write a specialized formatter that can convert from id to MaritalStatus object and vice versa. You'll find more information how to do it here: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/html/validation.html#format

[You could also send the id of the selected field and additionally its value in the hidden field and then try to build from those the MaritalStatus on the server side, but it is not elegant.]

Upvotes: 2

Related Questions