Sort Picklist Values in Lightning Component Salesforce | #Salesforce Tutorials


In this article you will learn to sort the values in Picklist in Lightning Component. You just have to add an additional line to your controller or helper of your Lightning Component.

In below code I am getting my Picklist values by "fetchPicklistValues" function. In the picklist I am having numeric values from 1 to 12.

Without sorting the result will be 1,10,11,12,2,3,4,5,6,7,8,9 but after sorting the result will be 1,2,3,4,5,6,7,8,9,10,11,12

Please check below code line number 18 for sorting.

Controller
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fetchPicklistValues: function(component, fieldName, elementId, plType) {
        var action = component.get("c.getselectOptions");
        action.setParams({
            "objObject": component.get("v.objInfo"),
            "fld": fieldName
        });
        var opts = [];
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
                var allValues = response.getReturnValue();
                    if (allValues != undefined && allValues.length > 0) {
                        opts.push({
                            class: "optionClass",
                            label: "--- None ---",
                            value: ""
                        });
                    }
                allValues.sort(function(a, b){return a - b});
                for (var i = 0; i < allValues.length; i++) {
                    opts.push({
                        class: "optionClass",
                        label: allValues[i],
                        value: allValues[i]
                    });
                }
                component.find(elementId).set("v.options", opts);
            }
            else{
                var errors = response.getError();
                console.log('###Error'+errors[0].message);
            }
        });
        $A.enqueueAction(action);
    }


Output

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 





Post a Comment

0 Comments