picklist

Sort Picklist Values in Lightning Component | 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 the 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

dont miss out iconDon't forget to check out: Top Salesforce Lightning Components to Improve Functionality

Please check below code line number 18 for sorting.

Controller

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

dont miss out iconCheck out another amazing blog by Kapil here: Formula to Get Time Zone Based on Area Code in Salesforce

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 

Also, check out some amazing videos by Kapil HERE.

Popular Salesforce Blogs