function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
prasad vivekprasad vivek 

Hi, I have a doubt regarding dual list box in lightning

Hi i have a doubt regarding  dual list box in lightning, on page load I am trying to assign selected values attribute by using a  list, but I am not able to do so. Can anyone help me on this,
My code is 
<aura:attribute name="GeneralList" type="List" default="[]" description="Genre Picklist Values"/>
    <aura:attribute name="selectedList" type="List" default="[]" description="Selected Genre Picklist Values"/>
     
    <div class="slds-m-around_xx-large">
        <lightning:dualListbox aura:id="select"
                               name="Genre"
                               label="Select"
                               sourceLabel="Available"
                               selectedLabel="Selected"
                               options="{!v.GeneralList}"
                               value="{!v.selectedList}"
                               onchange="{!c.handleChange}"/>
JS Controller

 doInit: function(component, event, helper) {
        var action = component.get("c.getPicklistValues");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS"){
                var result = response.getReturnValue();
                var picklistValues = [];
                var selectedlist = [];
                for (var i = 0; i < result.length-5; i++) {
                    picklistValues.push({
                        label: result[i],
                        value: result[i]
                    });
                }
                for (var i = 4; i < result.length; i++) {
                    
                    selectedlist.push({
                        label: result[i],
                        value: result[i]
                    });
                }
                alert('picklistValues'+JSON.stringify(picklistValues));
                component.set("v.GeneralList", picklistValues);
                // Hard coding is done 
                //alert('selectedlist'+ JSON.stringify(selectedlist));
                   component.set("v.selectedList",selectedlist);
                alert('get selected list'+JSON.stringify(component.get("v.selectedList")));
            }
        });
        $A.enqueueAction(action);
    }
Khan AnasKhan Anas (Salesforce Developers) 
Hi Prasad,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Component:
<aura:component controller="multiPicklistCtrl">
    <!--init handler event call "initialize" function on component load
        and fetch picklist values-->
    <aura:handler name="init" value="{! this }" action="{! c.initialize }"/>
    
   <!--Declare Attributes-->  
    <aura:attribute name="objInfo" type="account" default="{sobjectType : 'Account'}" />
	<aura:attribute name="listSkillsOptions" type="List" default="[]"/>
    <aura:attribute name="selectedSkillsItems" type="List" default="[]"/>
  
   <!-- lightning dualListbox component -->
    <lightning:dualListbox aura:id="selectOptions"
                           name="Skills"
                           label= "Select Skills" 
                           sourceLabel="Available Options" 
                           selectedLabel="Selected Options" 
                           options="{! v.listSkillsOptions }"
                           value="{! v.selectedSkillsItems }"
                           onchange="{! c.handleChange }"/>
    <br/>
    
    <lightning:button variant="brand" label="Selected Items" onclick="{!c.getSelectedItems }" />
</aura:component>

Controller:
({
    initialize: function(component, event, helper) {
       // call the fetchPickListVal helper function,
       // and pass (component, Field_API_Name, target_Attribute_Name_For_Store_Value)   
        helper.fetchPickListVal(component, 'Skills__c', 'listSkillsOptions');
    },
    handleChange: function (component, event) {
       // get the updated/changed values   
        var selectedOptionsList = event.getParam("value");
       // get the updated/changed source  
        var targetName = event.getSource().get("v.name");
       
        // update the selected itmes  
        if(targetName == 'Skills'){ 
            component.set("v.selectedSkillsItems" , selectedOptionsList);
        }
        
    },
    getSelectedItems : function(component,event,helper){
       // get selected items on button click 
        alert(component.get("v.selectedSkillsItems"));
    }
})

Helper:
({
	fetchPickListVal: function(component, fieldName,targetAttribute) {
      // call the apex class method and pass fieldApi name and object type 
        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();
                for (var i = 0; i < allValues.length; i++) {
                    opts.push({
                        label: allValues[i],
                        value: allValues[i]
                    });
                }
                component.set("v."+targetAttribute, opts);
            }else{
                alert('Callback Failed...');
            }
        });
        $A.enqueueAction(action);
    },
})

Apex:
public class multiPicklistCtrl {
    
    @AuraEnabled
    public static List < String > getselectOptions(sObject objObject, string fld) {
        system.debug('objObject --->' + objObject);
        system.debug('fld --->' + fld);
        List < String > allOpts = new list < String > ();
        // Get the object type of the SObject.
        Schema.sObjectType objType = objObject.getSObjectType();
        
        // Describe the SObject using its object type.
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
        
        // Get a map of fields for the SObject
        map < String, Schema.SObjectField > fieldMap = objDescribe.fields.getMap();
        
        // Get the list of picklist values for this field.
        list < Schema.PicklistEntry > values =
            fieldMap.get(fld).getDescribe().getPickListValues();
        
        // Add these values to the selectoption list.
        for (Schema.PicklistEntry a: values) {
            allOpts.add(a.getValue());
        }
        system.debug('allOpts ---->' + allOpts);
        allOpts.sort();
        return allOpts;
    }
    
}

Reference: http://sfdcmonkey.com/2018/02/25/fetch-multi-picklist-values-lightningduallistbox-component/

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas​​​​​​​
Deepali KulshresthaDeepali Kulshrestha
Hi prasad,

You just need to push result[i] direct into list(selectedlist) as given below:

   for (var i = 4; i < result.length; i++) {
                    
                   selectedlist.push(result[i]);
                }
                
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks.
Deepali Kulshrestha