开发者

Spring MVC bind comma separated list to multi-select

开发者 https://www.devze.com 2023-01-15 09:20 出处:网络
tl;dr: I have a custom object that isn\'t a Collection.How can I get Spring to bind it to a multiple select?

tl;dr: I have a custom object that isn't a Collection. How can I get Spring to bind it to a multiple select?

I have an object Field that contains a field called value, which is a String, with getters and setters. Sometimes the value field contains a single value and those will be displayed in a text box. Other times the value field will contain a comma separated list and that needs to be displayed in a multi select box.

I have a map of these fields (e.g. {"MY_MULTI_FIELD", Field.class} that I get as follows:

Text

  <form:input maxlength="200" path="fields[MY_TEXT_FIELD]" disabled="${springIsDisabled}" />

Multiselect

<form:select cssClass="required" path="fields[MY_MULTI_FIELD]" items="${blah}" size="5" multiple="true" disabled="${springIsDisabled}" />

I have a FieldEditor that I register in my controller

binder.registerCustomEditor(Field.class, new FieldEditor());

that looks like this

public class FieldEditor extends PropertyEditorSupport {

  @Override
  public String getAsText() {
    Field field = (Fie开发者_如何学JAVAld) getValue();
    return field.getValue();
  }

  @Override
  public void setAsText(String text) throws IllegalArgumentException {
    setValue(text);
  }

}

The case where I just have a text field works just fine. Also if just one item from the multiselect box is chosen it works fine.

The problem is when we choose multiple items from the multiselect box. When we view the form after saving it doesn't appear as if any values were chosen from the multiselect. The getAsText() returns the comma separated string, which of course doesn't match the value of any one of the option values but rather is a combination of several of them.

For example, if we choose

<option value="test">Test</option> <option value="test2">Test2</option>

the value field is "test,test2".

How do I get Spring to understand that if the option value is contained within the comma separated string then it should be selected?


I don't think the model object Field has the right structure for a multiple select.

0

精彩评论

暂无评论...
验证码 换一张
取 消