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
Fred13Fred13 

lightning:select to Iterate over list of strings

I have a list of strings that I want to display on my component.  The issue I am currently having is actually displaying the values in the attribute.

My attribute is: <aura:attribute name="groupnumbers" type="group_structure__c[]" />

My select field is: 
<lightning:layoutItem padding="around-small">
            <!-- Create a dropdown menu with options for Section code-->
            <lightning:select aura:id="selectGroupNum" label="GroupNum" name="sourceGroupNum" onchange="{!c.handleSelect}">
          			 <aura:iteration items="{!v.groupnumbers}" var="gs">
            		<option value="{!gs}">{!gs.label}</option>
        		 </aura:iteration>
            </lightning:select>
     	 </lightning:layoutItem>

I am certain that my option value is the issue.  How do I display the attribute when it is just a list of strings?  Also, can I set a default?

Thank you!!!!

Fred
Best Answer chosen by Fred13
Khan AnasKhan Anas (Salesforce Developers) 
Hi Fred,

I trust you are doing very well.

Please use <option value="{!gs}" text="{!gs}" /> 

Below is the sample code to dynamically fetch picklist values and insert the records. Picklist values are List of string.

Custom Object: Registration_Form__c

Component:
<aura:component controller="InsertPicklist_TaskSvrController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
	
    <aura:attribute name="PageHeading" type="String" default="Registration Form for Students"/>
    <aura:attribute name="RegForm" type="Registration_Form__c" default="{'sobjectType' : 'Registration_Form__c'}"/>
    <aura:attribute name="PercentPick" type="Registration_Form__c[]" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <div class="slds-m-top--xx-large">
    	<div class="slds-page-header">
    		<div class="slds-align--absolute-center">
        		<div class="slds-text-heading--large">       
    				{!v.PageHeading}
                </div>
        	</div>
    	</div>
    </div>
    <br/> <br/>
    
    <div class = "slds-size--3-of-8">
    	<lightning:input label="Enter Student Name" name="studentName" value="{!v.RegForm.Name}"/>
        <br/>
    	<lightning:input label="Enter Parents Name" name="parentName" value="{!v.RegForm.Parents_Name__c}"/>
        <br/>
    	<lightning:input label="Enter Class Name" name="className" value="{!v.RegForm.Class_Name__c}"/>
        <br/>
    	<lightning:input label="Enter Mobile Number" name="mobileNo" value="{!v.RegForm.Mobile_Number__c}"/>
        <br/>
        <lightning:select aura:id="PicklistId" label="Enter Last Class Percentage" name="percent" >
			<option value="" text="- None -" /> 
            <aura:iteration items="{!v.PercentPick}" var="per">
            	<option value="{!per}" text="{!per}" />  
        	</aura:iteration>
    	</lightning:select>
        <br/>
        <lightning:button label="Submit" onclick="{!c.doSubmit}"/>
        <lightning:button label="Submit and Open Detail Page" onclick="{!c.doSaveAndOpenDetail}"/>
    </div>
</aura:component>

Controller:
({
    doInit : function(component, event, helper){
        var action = component.get("c.getPicklist");
        var percent = component.find("PicklistId");
        var opts=[];
        action.setCallback(this, function(response) {
            var allValues = response.getReturnValue();
            console.log('allValues -- >> ' + allValues);
            component.set("v.PercentPick", allValues);
        });
        $A.enqueueAction(action); 
    },
    
	doSubmit : function(component, event, helper) {
		var regForm = component.get("v.RegForm");
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : regForm});
        action.setCallback(this, function(response) {
            var state = response.getState();
            
            if (state === "SUCCESS") {
                alert('Successfully Saved');
                component.set('v.RegForm','');
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
	},
    
    doSaveAndOpenDetail : function(component, event, helper) {
        var reg = component.get("v.RegForm");
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : reg});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                var navEvt = $A.get("e.force:navigateToSObject");
        		var myid = response.getReturnValue();
    			navEvt.setParams({
            		"recordId": myid, 
            		"slideDevName": "detail"
    			});
    			navEvt.fire();
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
    }
})

CSS:
.THIS {

}

.THIS.slds-size--3-of-8 {
    
    margin-left: 430px;
}

.THIS label.slds-form-element__label{
    
    font-size: 1.00rem;
    color: blue;
}

Apex Controller:
public class InsertPicklist_TaskSvrController {
	
    @AuraEnabled
    public static List<String> getPicklist(){
        List<String> options = new List<String>();
        Schema.DescribeFieldResult fieldResult = Registration_Form__c.Percentage__c.getDescribe();
        System.debug('fieldResult---->>> ' + fieldResult);
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        System.debug('pList---->>> ' + pList);
        for (Schema.PicklistEntry p: pList) {
            options.add(p.getLabel());
        }
        System.debug('options---->>> ' + options);
        return options;
    }
    
    @AuraEnabled
    public static void saveDetails(Registration_Form__c regForm1){
    	// DML operation to save RegForm Details   
    	INSERT regForm1;
    }
}

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.

Thanks and Regards,
Khan Anas​

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Fred,

I trust you are doing very well.

Please use <option value="{!gs}" text="{!gs}" /> 

Below is the sample code to dynamically fetch picklist values and insert the records. Picklist values are List of string.

Custom Object: Registration_Form__c

Component:
<aura:component controller="InsertPicklist_TaskSvrController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
	
    <aura:attribute name="PageHeading" type="String" default="Registration Form for Students"/>
    <aura:attribute name="RegForm" type="Registration_Form__c" default="{'sobjectType' : 'Registration_Form__c'}"/>
    <aura:attribute name="PercentPick" type="Registration_Form__c[]" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <div class="slds-m-top--xx-large">
    	<div class="slds-page-header">
    		<div class="slds-align--absolute-center">
        		<div class="slds-text-heading--large">       
    				{!v.PageHeading}
                </div>
        	</div>
    	</div>
    </div>
    <br/> <br/>
    
    <div class = "slds-size--3-of-8">
    	<lightning:input label="Enter Student Name" name="studentName" value="{!v.RegForm.Name}"/>
        <br/>
    	<lightning:input label="Enter Parents Name" name="parentName" value="{!v.RegForm.Parents_Name__c}"/>
        <br/>
    	<lightning:input label="Enter Class Name" name="className" value="{!v.RegForm.Class_Name__c}"/>
        <br/>
    	<lightning:input label="Enter Mobile Number" name="mobileNo" value="{!v.RegForm.Mobile_Number__c}"/>
        <br/>
        <lightning:select aura:id="PicklistId" label="Enter Last Class Percentage" name="percent" >
			<option value="" text="- None -" /> 
            <aura:iteration items="{!v.PercentPick}" var="per">
            	<option value="{!per}" text="{!per}" />  
        	</aura:iteration>
    	</lightning:select>
        <br/>
        <lightning:button label="Submit" onclick="{!c.doSubmit}"/>
        <lightning:button label="Submit and Open Detail Page" onclick="{!c.doSaveAndOpenDetail}"/>
    </div>
</aura:component>

Controller:
({
    doInit : function(component, event, helper){
        var action = component.get("c.getPicklist");
        var percent = component.find("PicklistId");
        var opts=[];
        action.setCallback(this, function(response) {
            var allValues = response.getReturnValue();
            console.log('allValues -- >> ' + allValues);
            component.set("v.PercentPick", allValues);
        });
        $A.enqueueAction(action); 
    },
    
	doSubmit : function(component, event, helper) {
		var regForm = component.get("v.RegForm");
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : regForm});
        action.setCallback(this, function(response) {
            var state = response.getState();
            
            if (state === "SUCCESS") {
                alert('Successfully Saved');
                component.set('v.RegForm','');
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
	},
    
    doSaveAndOpenDetail : function(component, event, helper) {
        var reg = component.get("v.RegForm");
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : reg});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                var navEvt = $A.get("e.force:navigateToSObject");
        		var myid = response.getReturnValue();
    			navEvt.setParams({
            		"recordId": myid, 
            		"slideDevName": "detail"
    			});
    			navEvt.fire();
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
    }
})

CSS:
.THIS {

}

.THIS.slds-size--3-of-8 {
    
    margin-left: 430px;
}

.THIS label.slds-form-element__label{
    
    font-size: 1.00rem;
    color: blue;
}

Apex Controller:
public class InsertPicklist_TaskSvrController {
	
    @AuraEnabled
    public static List<String> getPicklist(){
        List<String> options = new List<String>();
        Schema.DescribeFieldResult fieldResult = Registration_Form__c.Percentage__c.getDescribe();
        System.debug('fieldResult---->>> ' + fieldResult);
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        System.debug('pList---->>> ' + pList);
        for (Schema.PicklistEntry p: pList) {
            options.add(p.getLabel());
        }
        System.debug('options---->>> ' + options);
        return options;
    }
    
    @AuraEnabled
    public static void saveDetails(Registration_Form__c regForm1){
    	// DML operation to save RegForm Details   
    	INSERT regForm1;
    }
}

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.

Thanks and Regards,
Khan Anas​
This was selected as the best answer
Ajay K DubediAjay K Dubedi
Hi Fred,
Here is a solution to your Problem:
        
        ---------Component--------
        
<aura:component controller="AuraUtility">
    <aura:attribute name="fieldList" type="String[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div class="slds-m-vertical_xx-large slds-m-horizontal_xx-large">
        <aura:if isTrue="{!v.fieldList.length > 0}">
            <table class="slds-table slds-table_bordered slds-table_cell-buffer" >
                <thead>
                    <tr class="slds-text-title_caps">
                        <th scope="col" >
                            <div class="slds-truncate" title="Field Name"><b>Field Name</b></div>
                        </th>
                    </tr>
                </thead> 
                <tbody>
                    <tr>
                        <td data-label="Fields Name" >
                            <lightning:select name="select1">
                                <aura:iteration items="{!v.fieldList}" var="fld" >
                                    <option value="{!fld}" text="{!fld}"></option>
                                </aura:iteration>
                            </lightning:select>
                        </td>
                    </tr>
                </tbody>
            </table>
        </aura:if>    
    </div>
</aura:component>


            ---------Controller_JS--------
            
({
    doInit : function(component, event, helper) {
        console.log('helper Calling>>>>>>>');
        helper.displayField_helper(component, event, helper);    
    }
})

            ---------Helper_JS--------

({
    displayField_helper : function(component, event, helper) {
        console.log('>>>>>>>>>>>>>Enter in FieldFunc.');
        var action = component.get("c.displayFieldLabel");
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
                var allValues = response.getReturnValue();
                console.log('Fields List>>>>>>>>>>>>.'+allValues);
                component.set("v.fieldList", allValues);
                console.log('Fields List>>>>>>>>>>>>.'+component.get("v.fieldList"));
            }    
        });
        $A.enqueueAction(action);        
    }
})        


        --------Aura Utility_Apex---------------
        
public class AuraUtility {        
    @AuraEnabled
        public static List< String > displayFieldLabel() {
            List<string> lstfield  =new list<string>(); 
            Schema.SObjectType objType = Schema.Account.getSObjectType(); 
            Schema.DescribeSobjectResult objResult = objType.getDescribe();
            Map<String, Schema.SObjectField> mapOfField = objResult.fields.getMap(); 
            for(String s : mapOfField.keyset()){
                lstfield.add(mapOfField.get(s).getDescribe().getLabel());
            }
            system.debug('List of Fields>>>>>>'+ lstfield);
            lstfield.sort();
            return lstfield;
        }
}  
 
Please mark this as Best Answer if you find this solution helpful.
 
Thank You
Ajay Dubedi    
Fred13Fred13
Thank you both for your replies!   That did the trick!!!
Fred13Fred13
HI.  Just one more thing please, how do I set the default value to "All" which is the first item on the list? thanks!!!
Khan AnasKhan Anas (Salesforce Developers) 
Hi Fred,

If you use this code, it will display the first item in the picklist.
<lightning:select aura:id="selectGroupNum" label="GroupNum" name="sourceGroupNum" onchange="{!c.handleSelect}">
          			 <aura:iteration items="{!v.groupnumbers}" var="gs">
            		<option value="{!gs}" text="{!gs}" />
        		 </aura:iteration>
            </lightning:select>

If you want 'None' in the picklist, you can use below code:
<lightning:select aura:id="selectGroupNum" label="GroupNum" name="sourceGroupNum" onchange="{!c.handleSelect}">
                                 <option value="" text="- None -" /> 
          			 <aura:iteration items="{!v.groupnumbers}" var="gs">
            		<option value="{!gs}" text="{!gs}" />
        		 </aura:iteration>
            </lightning:select>

Regards,
Khan Anas
Fred13Fred13
Thanks for the reply Khan.  While it is displaying the first value in the list, its not assigning a value to the select list.  By defult the value is showing my "All" value.  However, when I view the value of that list, its null.  I'm hoping to set a default value for the select field in addition to showing that value.  thanks!!

Fred