Eine Visualforce Seite enthält diverse Options-, Checkboxen-, Auswahlfelder deren Inhalt dynamisch vom Controller in Form von Listen list<SelectOption> aufgebaut wird.
Die Einträge sind unsortiert. Dummerweise gibt es von Salesforce immer noch keine (brauchbare) Funktion zum Sortieren von SelectOptions nach Label.
Die im Internet gefundenen Sort-Funktionen haben auch nur teilweise funktioniert.
Abhinav Gupta hat in seinem Blog http://www.tgerm.com/2011/08/salesforce-apex-selectoption-sort.html eine simple Klasse vorgestellt, die ich letztendlich nach einer kleinen Modifikation:
Aufruf:
Klasse:
Die Einträge sind unsortiert. Dummerweise gibt es von Salesforce immer noch keine (brauchbare) Funktion zum Sortieren von SelectOptions nach Label.
Die im Internet gefundenen Sort-Funktionen haben auch nur teilweise funktioniert.
Abhinav Gupta hat in seinem Blog http://www.tgerm.com/2011/08/salesforce-apex-selectoption-sort.html eine simple Klasse vorgestellt, die ich letztendlich nach einer kleinen Modifikation:
opt.getLabel() +
ersetzt durch opt.getLabel().toLowerCase() + ' ' +
eingesetzt habe.Aufruf:
list<SelectOption> F_lstDepartment = new list<SelectOption>();
lstDepartment.add('id1', 'Dev'');
lstDepartment.add('id2', '---Please Choose---');
lstDepartment.add('id3', 'Marketing Services');
SelectOptionSorter.doSort(lstDepartment, SelectOptionSorter.FieldToSort.Label);
Klasse:
global class SelectOptionSorter {
/**
Sort field to use in SelectOption i.e. Label or Value
*/
global enum FieldToSort {
Label, Value
}
global static void doSort(List<selectoption> opts, FieldToSort sortField) {
if(opts != null){
Map<string selectoption=""> mapping = new Map<string selectoption="">();
// Suffix to avoid duplicate values like same labels or values are in inbound list
Integer suffix = 1;
for (Selectoption opt : opts) {
if (sortField == FieldToSort.Label) {
mapping.put( // Done this cryptic to save scriptlines, if this loop executes 10000 times
// it would every script statement would add 1, so 3 would lead to 30000.
(opt.getLabel().toLowerCase() + ' ' + suffix++), // Key using Label + Suffix Counter
opt);
} else {
mapping.put(
(opt.getValue() + suffix++), // Key using Label + Suffix Counter
opt);
}
}
List<string> sortKeys = new List<string>();
sortKeys.addAll(mapping.keySet());
sortKeys.sort();
// clear the original collection to rebuilt it
opts.clear();
for (String key : sortKeys) {
opts.add(mapping.get(key));
}
}
}
}

Kommentare
Kommentar veröffentlichen