Initially default selected value returns null during button click in aura component

auraaura-attributeaura-ifaura-iterationlightning-aura-components

I made Temp Reservation as default selected option. Initially when i click save button it returns null instead of Temp Reservation. once i change the option it returns the selected value. Anyone helps me to solve this.

Thanks in Advance.

component file

<aura:attribute name="workStatusOption" type="List" default="[]" description="" />
<aura:attribute name="workStatusSelectVal" type="String" default="Temp Reservation"/>

<lightning:select name="status" label="" aura:id="workstatus" required="true" >
    <aura:iteration items="{!v.workStatusOption}" var="item">
          <aura:if isTrue="{!v.workStatusSelectVal == item}">
                <option text="{!item}" value="{!item}" selected="selected"/>
            <aura:set attribute="else">
                <option text="{!item}" value="{!item}" />
            </aura:set>
          </aura:if>
    </aura:iteration>
</lightning:select>

<button class="slds-button slds-button_brand" onclick="{!c.doSave}">Save</button>

controller file

doInit : function(component, event, helper) {
    var action = component.get("c.getPickListOption");
    action.setParams({objectName : "StockRecord__c", fieldName : "WorkStatus__c"});
    action.setCallback(this,function(response){
        var state = response.getState();
        if (state === "SUCCESS") { 
            var result = response.getReturnValue();
            component.set("v.workStatusOption", result);  
        } else if (state === "ERROR") {
            var errors = response.getError();
        }
    });
    $A.enqueueAction(action);
},

doSave: function(cmp, evt, helper) {
    var workStatus = cmp.find("workstatus").get("v.value");
    alert(workStatus);
},

Apex Class

@AuraEnabled
public static List<String> getPickListOption(String objectName, String fieldName){  
    List<String> allOpts = new List<String>();
    Schema.SObjectType t  = Schema.getGlobalDescribe().get(objectName);
    SObject obj = t.newSObject();
    Schema.sObjectType objType = obj.getSObjectType();
    Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
    map <String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
    list <Schema.PicklistEntry> values = fieldMap.get(fieldName).getDescribe().getPickListValues();
    for (Schema.PicklistEntry a: values) {
        allOpts.add(a.getLabel());
    }
    allOpts.sort();
    return allOpts;
}

Best Answer

In the lightning:select you need to set value="{!v. workStatusSelectVal}" initially and then you will be able to get it. When you change the value, it will also change.

Related Topic