As we know, the sorting method for SelectOption list is that sort the value first and then Label. Usually we need sort by label only or value. So here we have a workaround for this.
Solution:
We should have a SelectOptionUtil class for the sorting.
global enum FieldToSort {
Label, Value
}
global static void doSort(List<Selectoption> opts, FieldToSort sortField) {
Map<String, Selectoption> mapping = new Map<String, Selectoption>();
Integer suffix = 1;
for (Selectoption opt : opts) {
if (sortField == FieldToSort.Label) {
mapping.put((opt.getLabel() + suffix++), opt);
} else {
mapping.put((opt.getValue() + suffix++),opt);
}
}
List<String> sortKeys = new List<String>();
sortKeys.addAll(mapping.keySet());
sortKeys.sort();
opts.clear();
for (String key : sortKeys) {
opts.add(mapping.get(key));
}
}