These are the changes I made to make the Select2 (tag mode) component working with Spring MVC:
Select2 Tag Mode (JavaScript)
$('#issue-tags').editable({
pk: 22,
name: 'tagsMap',
placement: 'top',
mode: 'popup',
emptytext: 'No hay etiquetas definidas',
inputclass: 'input-large',
select2: {
tags: ${allTags},
tokenSeparators: [",", " "],
id: function (item) {
return item.text;
}
},
ajaxOptions: {
type: 'put'
}
});
Where tagsMap
is an object of my DTO class that holds the tags upon submit:
Select 2 Tag Mode (HTML input)
<a id="issue-tags" href="#" data-type="select2">${tagsByObject}</a>
Where tagsByObject
contains a string of tags separated by commas, used by Select2 to display the specific tags of my object.
Java DTO
public class MyObjectDTO implements Serializable {
private List<String> tags = new ArrayList<String>();
private Map<String, Object> tagsMap = new HashMap<String, Object>();
...
}
Where allTags
is a JSON object parsed as a String, which populates the dropdown-menu of the Select2 component, displaying all current tags persisted in my database.
Spring MVC Controller
@RequestMapping(value="/showPage", method = RequestMethod.GET)
public String showPage(Model model, HttpServletRequest request){
...
List<String> myTags = myObjectDTO.getTags();
String tagsByComma = StringUtils.EMPTY;
String allTags = StringUtils.EMPTY;
if(!myTags.isEmpty()){
for(int i = 0; i < myTags.size(); i++){
tagsByComma += myTags.get(i) + ", ";
}
tagsByComma = tagsByComma.substring(0, tagsByComma.length() -2);
}
List<String> dbTags = myService.getTags();
JSONArray array = new JSONArray();
for(String s : dbTags){
JSONObject obj = new JSONObject();
obj.put("id", dbTags.indexOf(s));
obj.put("text", s);
array.put(obj);
}
allTags = array.toString();
model.addAttribute("tagsByObject", tagsByComma);
model.addAttribute("allTags", allTags.length() == 0 ? "[{}]" : allTags);
...
}
Submit function remains untouched.